1. 程式人生 > >os.walk()與os.path.join()遍歷目錄與檔案

os.walk()與os.path.join()遍歷目錄與檔案

os.walk()

os.walk() 方法用於通過在目錄樹中游走輸出在目錄中的檔名,向上或者向下。

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

top 為要遍歷的目錄:

topdown = True,優先遍歷top目錄,再遍歷子目錄,可選引數

onerror -- 可選, 需要一個 callable 物件,當 walk 需要異常時,會呼叫。

followlinks -- 可選, 如果為 True,則會遍歷目錄下的快捷方式(linux 下是 symbolic link)實際所指的目錄(預設關閉)。

得到的是一個元組(root,dirs,files)

root  當前遍歷到的目錄

dirs  當前目錄下的子目錄,是一個list

files 當前目錄下的檔案,是一個list

os.path.join()

將多個路徑組合後返回

語法:os.path.join(path1[,path2[,path3[,...[,pathN]]]])

注意:第一個絕對路徑之前的引數將會被忽略

例子

目錄結構 

D:\\xiaogaojianghu_jinyong

-- 0.txt

-- 1.txt

-- 2.txt

-- 3.txt

-- 4.txt

-- a

    -- 5.txt

    -- 6.txt

    -- 7.txt

    -- 8.txt

for root, dirs, files in os.walk('D:\\xiaoaojianghu_jinyong'):
    for name in files:
        fileName = os.path.join(root,name)
        modifiedTime = time.localtime(os.stat(fileName).st_mtime)
        createdTime = time.localtime(os.stat(fileName).st_ctime)
        mTime = time.strftime('%Y-%m-%d %H:%M:%S', modifiedTime)
        cTime = time.strftime('%Y-%m-%d %H:%M:%S', createdTime)        
        print("fileName " + fileName)
        print("modifiedTime " + mTime)
        print("createdTime " + cTime + '\n')

輸出

modifiedTime 2017-12-11 00:13:11
createdTime 2017-09-11 19:25:22
fileName D:\xiaoaojianghu_jinyong\0.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:20:58

fileName D:\xiaoaojianghu_jinyong\1.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

fileName D:\xiaoaojianghu_jinyong\2.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

fileName D:\xiaoaojianghu_jinyong\3.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

fileName D:\xiaoaojianghu_jinyong\4.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

fileName D:\xiaoaojianghu_jinyong\a\5.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

fileName D:\xiaoaojianghu_jinyong\a\6.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

fileName D:\xiaoaojianghu_jinyong\a\7.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

fileName D:\xiaoaojianghu_jinyong\a\8.txt
modifiedTime 2018-11-12 20:08:33
createdTime 2018-11-04 21:27:42

參考