1. 程式人生 > >Python檔案遍歷的三種方法

Python檔案遍歷的三種方法

1. os.path.walk()

這是一個傳統的用法。

walk(root,callable,args)方法有三個引數:要遍歷的目錄,回撥函式,回撥函式的引數(元組形式)。

呼叫的過程是遍歷目錄下的檔案或目錄,每遍歷一個目錄,呼叫回撥函式,並把args作為引數傳遞給回撥函式。

回撥函式定義時也有三個引數,比如示例中的func中的三個引數,分別為walk傳來的引數、目錄的路徑、目錄下的檔案列表(只有檔名,不是完整路徑)。請看示例:

import os
s = os.sep #根據unix或win,s為\或/
root = "d:" + s + "ll" + s #要遍歷的目錄
def func(args,dire,fis): #回撥函式的定義
    for f in fis:
        fname = os.path.splitext(f)  #分割檔名為名字和副檔名的二元組
        new = fname[0] + 'b' + fname[1]  #改名字
        os.rename(os.path.join(dire,f),os.path.join(dire,new)) #重新命名
os.path.walk(root,func,()) #遍歷

2. os.walk()

原型為:os.walk(top, topdown=True, onerror=None, followlinks=False)

我們一般只使用第一個引數。(topdown指明遍歷的順序)
該方法對於每個目錄返回一個三元組,(dirpath, dirnames, filenames)。第一個是路徑,第二個是路徑下面的目錄,第三個是路徑下面的非目錄(對於windows來說也就是檔案)。請看示例:

import os
s = os.sep
root = "d:" + s + "ll" + s 
for rt, dirs, files in os.walk(root):
    for f in files:
        fname = os.path.splitext(f)
        new = fname[0] + 'b' + fname[1]
        os.rename(os.path.join(rt,f),os.path.join(rt,new))

3. listdir

可以使用os模組下的幾個方法組合起來進行遍歷。請看示例:

import os
s = os.sep
root = "d:" + s + "ll" + s
for i in os.listdir(root):
    if os.path.isfile(os.path.join(root,i)):
        print i

這裡需要注意的是,其中的i是目錄或檔名,不是完整的路徑,在使用時要結合os.path.join()方法還原完整路徑。