2008年6月30日 星期一

Python/Perl File operation




上周寫了一堆在Python檢查directory & file的函數(用c的方法):

import os
import sys
from stat import *

def checkIsDir(strDir):
try:
if ( S_ISDIR(os.stat(strDir)[ST_MODE]) ):
return 1
else:
return 0
except OSError, err:
return 0

def checkIsFile(strFile):
try:
if (S_ISREG(os.stat(strFile)[ST_MODE]) ):
return 1
else:
return 0
except OSError, err:
return 0

還得用try , except 來包咧…

剛剛居然讓我試出超簡單的方法:
import os

strPtnFile = os.path.join(r".\\", "BF.ptn")
print "\nPattern : " + strPtnFile + "\n"

if ( os.path.isfile(strPtnFile) ):
print "File exists!\n"
else:
print "File doesn't exists!\n"

strPath = os.path.join
if ( os.path.isdir(strPath) ):
print "Dir exists!\n"
else:
print "Dir doesn't exists!\n"



突然覺得有點「囧」掉了…熟跟不熟,差太多了
再想想用perl

# CheckIsFile
print "File exists!\n" if ( -f filename ) ;

# CheckIsDir
print "Dir exists!\n" if ( -d pathname ) ;

# CheckIsEmptyFile
print "File with zero size!\n" if ( -z filename ) ;

# GetFileSize
$size = -s filename ;
print "file size is $size\n" ;


太多了,上面列幾個比較常用的~~~

沒有留言: