檔案與目錄的處理,雖然也能靠系統命令完成,但 Python 為了讓開發者以程式化方式處理這些工作,提供了大量內建函式。更棒的是,這些函式在 Unix、Windows 與 Macintosh 平台上的用法完全一致。
本文逐一示範:列出檔案、判定檔案/目錄/連結、取出大小與日期、刪除檔案與目錄、複製與移動、拆解完整路徑,以及建立目錄與遍歷目錄樹。
想列出當前目錄中所有 .jpg 或 .gif,可以用 glob 模組:
import glob
filelist = glob.glob('*.jpg') + glob.glob('*.gif')
glob 函式的參數即為要顯示的檔案類型,寫法採 UNIX shell 風格的通配符;詳細規則可參考 fnmatch 模組文件。
若要列出某目錄中的全部檔案,改用 os.listdir:
files = os.listdir(r'C:\hpl\scripting\src\py\intro') #適用於 Windows
files = os.listdir('/home/hpl/scripting/src/py/intro') #適用於 Unix
# 跨平台版本:
files = os.listdir(os.path.join(os.environ['scripting'],
'src', 'py', 'intro'))
files = os.listdir(os.curdir) # 當前目錄中的所有文件
files = glob.glob('*') + glob.glob('.*')
檔名、目錄名與連結名都是字串,那要如何判斷某個字串究竟指向一般檔案、目錄還是連結?用 os.path 的三個函式即可:
print myfile, '是一個', if os.path.isfile(myfile): print 'plain file' if os.path.isdir(myfile): print 'directory' if os.path.islink(myfile): print 'link'
接著可以查詢日期與大小:
time_of_last_access = os.path.getatime(myfile) time_of_last_modification = os.path.getmtime(myfile) size = os.path.getsize(myfile)
時間以秒為單位,從 1970 年 1 月 1 日起算。要換算成「最後存取距今幾天」:
import time # time.time()返回當前時間 age_in_days = (time.time()-time_of_last_access)/(60*60*24)
需要更詳細的資訊時,用 os.stat 搭配 stat 模組:
import stat myfile_stat = os.stat(myfile) size = myfile_stat[stat.ST_SIZE] mode = myfile_stat[stat.ST_MODE] if stat.S_ISREG(mode): print '%(myfile)是一個常規文件,大小為 %(size)d 字節' % vars()
若要測試讀、寫、執行權限,用 os.access:
if os.access(myfile, os.W_OK): print myfile, '具有寫權限' if os.access(myfile, os.R_OK | os.W_OK | os.X_OK): print myfile, '具有讀、寫以及執行權限'
這類測試對 CGI 腳本特別有用。
刪除單一檔案用 os.remove,例如 os.remove('mydata.dat');它的別名是 os.unlink,不過名稱與傳統 UNIX/Perl 的清除函式重名。批次刪除可以搭配 glob:
for file in glob.glob('*.jpg') + glob.glob('*.gif'):
os.remove(file)
只有在目錄內容已清空時才能用 rmdir 刪除。若想連同內容一起刪掉整棵目錄樹,用 shutil 的 rmtree:
shutil.rmtree('mydir') #相當於 UNIX 的 rm -rf mydir
也可以自訂一個函式,讓檔案與目錄一視同仁:
remove('my.dat') #刪除單個檔案 my.dat
remove('mytree') #刪除單個目錄樹 mytree
# 通過字符串列表中的名稱來刪除多個文件/目錄樹:
remove(glob.glob('*.tmp') + glob.glob('*.temp'))
remove(['my.dat','mydir','yourdir'] + glob.glob('*.data'))
remove 函式的實作:
def remove(files):
"""刪除一個或多個文件和/或目錄。"""
if isinstance(files, str): # files是個字符串嗎?
files = [files] # 把files從字符串轉為列表
if not isinstance(files, list): # files不是列表嗎?
files = list(files)
for file in files:
if os.path.isdir(file):
shutil.rmtree(file)
elif os.path.isfile(file):
os.remove(file)
驗證它的彈性:
# 建立10個目錄tmp_* ,以及10個文件tmp__*:
for i in range(10):
os.mkdir('tmp_'+str(i))
f = open('tmp__'+str(i), 'w'); f.close()
remove('tmp_1') # tmp_1為目錄
remove(glob.glob('tmp_[0-9]') + glob.glob('tmp__[0-9]'))
附带一個提醒:實作中的 if not isinstance(files, list) 其實過於嚴格。真正需要的只是一個可遍歷的檔案/目錄名序列,無論它存在 list、tuple 還是陣列裡都無妨,因此更好的寫法是 if not operator.isSequenceType(files)。
import shutil shutil.copy(myfile, tmpfile) #拷貝最後訪問時間和最後修改時間: shutil.copy2(myfile, tmpfile) # 拷貝一個目錄樹: shutil.copytree(root_of_tree, destination_dir, True)
copytree 的第三個參數決定對符號連結的處理:True 保留連結,False 則以實體檔案副本取代。
Python 對跨平台路徑組成的支援相當好:os.path.join 會使用正確的分界符(UNIX 與 Mac OS X 用 /,Windows 用 \),而 os.curdir 與 os.pardir 分別代表當前目錄與父目錄。像下面這個 UNIX 命令:
cp ../f1.c .
可以寫成跨平台版本:
shutil.copy(os.path.join(os.pardir,os.pardir,'f1.c'), os.curdir)
重新命名用 os.rename:
os.rename(myfile, 'tmp.1') # 將myfile重命名為'tmp.1'
它也能在同一檔案系統內移動檔案:
os.rename(myfile, os.path.join(d, myfile)) # 把 myfile 移到目錄 d
跨檔案系統移動時,最安全的做法是先複製再刪除原檔:
shutil.copy2(myfile, os.path.join(d, myfile)) os.remove(myfile)
假設 fname 存著完整路徑,例如 /usr/home/hpl/scripting/python/intro/hw.py,要拆成基本名稱與目錄名:
basename = os.path.basename(fname) dirname = os.path.dirname(fname) # 或 dirname, basename = os.path.split(fname)
副檔名則用 splitext 取出:
root, extension = os.path.splitext(fname)
如此 .py 會被指派給 extension,其餘部分給 root。若不想要點號,用 os.path.splitext(fname)[1][1:] 即可。
要把任意檔案 f 的副檔名改成 ext:
newfile = os.path.splitext(f)[0] + ext
更具體的例子:
>>> f = '/some/path/case2.data_source' >>> moviefile = os.path.basename(os.path.splitext(f)[0] + '.mpg') >>> moviefile 'case2.mpg'
origdir = os.getcwd() # 將當前位置記下來 newdir = os.path.join(os.pardir, 'mynewdir') if not os.path.isdir(newdir): os.mkdir(newdir) # 或者os.mkdir(newdir,'0755') os.chdir(newdir) ... os.chdir(origdir) # 返回原目錄 os.chdir(os.environ['HOME']) # 移到主目錄
若想在自己的主目錄下建立 py/src/test1,而三層目錄都不存在,用 mkdir 得跑三次;改用 makedirs 一次就能建好整串:
os.makedirs(os.path.join(os.environ['HOME'],'py','src','test1'))
下面的呼叫會遍歷 root 目錄樹,對每個目錄名 dirname 呼叫 myfunc(arg, dirname, files),其中 files 是該目錄中的檔名列表(可由 os.listdir(dirname) 取得),arg 則是呼叫端傳入的參數。對 UNIX 使用者而言,跨平台的 os.path.walk 相當於 find 命令。
最簡單的示範:
def ls(arg, dirname, files): print dirname, 'has the files', files os.path.walk(os.environ['HOME'], ls, None)
本例中 arg 並非必要,因此傳 None。若要列出主目錄中所有大於 1Mb 的檔案:
def checksize1(arg, dirname, files):
for file in files:
filepath = os.path.join(dirname, file)
if os.path.isfile(filepath):
size = os.path.getsize(filepath)
if size > 1000000:
size_in_Mb = size/1000000.0
arg.append((size_in_Mb, filename))
bigfiles = []
root = os.environ['HOME']
os.path.walk(root, checksize1, bigfiles)
for size, name in bigfiles:
print name, '大小為', size, 'Mb'
這裡用 arg 建立一個由 2 元組組成的 list,每個 2 元組存放檔案尺寸(MB)與完整路徑。若要在所有目錄的呼叫中修改 arg,arg 必須是可變的資料結構。
參數 dirname 是目前正被拜訪的目錄絕對路徑,files 中的檔名則是相對於 dirname 的相對路徑。遍歷期間當前工作目錄並未改變,腳本仍停在啟動時的目錄——這正是必須把 filepath 組合成帶 dirname 的絕對路徑的原因。若想切換工作目錄,在函式中暫存、切換、再還原即可:
def somefunc(arg, dirname, files): origdir = os.getcwd(); os.chdir(dirname) ... os.chdir(origdir) os.path.walk(root, somefunc, arg)
當然,你也可以自己寫出替代品。下面的 find 函式針對「每個檔案」而非「每個目錄」呼叫自訂函式:
def find(func, rootdir, arg=None):
# 對rootdir目錄中的每個文件調用func
files = os.listdir(rootdir) # 獲取rootdir目錄中的所有文件
files.sort(lambda a, b: cmp(a.lower(), b.lower()))
for file in files:
fullpath = os.path.join(rootdir, file)
if os.path.islink(fullpath):
pass
elif os.path.isdir(fullpath):
find(func, fullpath, arg)
elif os.path.isfile(fullpath):
func(fullpath, arg)
else:
print 'find: cannot treat ', fullpath
此函式可從 scitools 模組取得。與 os.path.walk 不同,find 以大小寫敏感的字母順序存取檔案與目錄。用它列出所有大於 1Mb 的檔案:
def checksize2(fullpath, bigfiles):
size = os.path.getsize(fullpath)
if size > 1000000:
bigfiles.append('%.2fMb %s' % (size/1000000.0, fullpath))
bigfiles = []
root = os.environ['HOME']
find(checksize2, root, bigfiles)
for fileinfo in bigfiles:
print fileinfo
arg 帶來了極大的彈性——你可以用它同時承載輸入資料與結果結構。下一例會收集所有超過指定大小、且副檔名符合條件的檔案,並依大小排序輸出:
bigfiles = {'filelist': [], # 文件名和大小列表
'extensions': ('.*ps', '.tiff', '.bmp'),
'size_limit': 1000000, # 1 Mb
}
find(checksize3, os.environ['HOME'], bigfiles)
def checksize3(fullpath, arg):
treat_file = False
ext = os.path.splitext(fullpath)[1]
import fnmatch # Unix的shell風格的通配符匹配
for s in arg['extensions']:
if fnmatch.fnmatch(ext, s):
treat_file = True # fullpath帶有正確的擴展名
size = os.path.getsize(fullpath)
if treat_file and size > arg['size_limit']:
size = '%.2fMb' % (size/1000000.0) # 打印
arg['filelist'].append({'size': size, 'name': fullpath})
# 按照大小排列文件
def filesort(a, b):
return cmp(float(a['size'][:-2]), float(b['size'][:-2]))
bigfiles['filelist'].sort(filesort)
bigfiles['filelist'].reverse()
for fileinfo in bigfiles['filelist']:
print fileinfo['name'], fileinfo['size']
排序函式中,list 的每個元素是一個字典,鍵 size 存的是字串,比較前必須先去掉單位 Mb(最後兩個字元)並轉成浮點數。
檔案與目錄的處理雖可用系統命令完成,但 Python 提供了大量內建函式,讓開發能以程式化方式處理,而且跨 Unix、Windows 與 Macintosh 用法一致。本文依序示範了顯示目錄內容、判定檔案類型、取得大小與日期、刪除檔案與目錄、複製與移動、拆解路徑名,以及目錄的建立與遍歷。
Python解析xml文檔實例 https://www.linuxidc.com/Linux/2012-02/54760.htm
《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] https://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 https://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 https://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡