Python之os.walk()方法

os.walk方法,主要用來遍歷一個目錄內各個子目錄和子文件。

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

可以得到一個三元tupple(dirpath, dirnames, filenames), 

 

第一個爲起始路徑,第二個爲起始路徑下的文件夾,第三個是起始路徑下的文件。

dirpath 是一個string,代表目錄的路徑,

dirnames 是一個list,包含了dirpath下所有子目錄的名字。

filenames 是一個list,包含了非目錄文件的名字。

這些名字不包含路徑信息,如果需要得到全路徑,需要使用os.path.join(dirpath, name).

通過for循環自動完成遞歸枚舉

例如:

F:\aaa 目錄是這樣的文件目錄結構

F:\aaa

|--------1.txt

|--------2.txt

|--------3.txt

|--------4(子文件夾)

         |-------5.txt

         |-------6.txt

         |-------7.txt

 

分別打印各個參數的實際值

#!/usr/bin/env python  
# 2.py  
# use UTF-8  
# Python 3.3.0  
  
# os.walk()的使用  
import os  
  
# 枚舉dirPath目錄下的所有文件  
  
def main():  
#begin  
    fileDir = "F:" + os.sep + "aaa"     # 查找F:\aaa 目錄下    
    for root, dirs, files in os.walk(fileDir):  
    #begin  
        print(root)  
        print(dirs)  
        print(files)  
    #end  
    os.system("pause")  
#end  
  
if __name__ == '__main__':  
#begin  
    main()  
#end  
  
  
# 輸出  
# F:\aaa  
# ['4']  
# ['1.txt', '2.txt', '3.txt']  
# F:\aaa\4  
# []  
# ['5.txt', '6.txt', '7.txt']  

你也可以這樣,用元組a,通過for循環即可完成目錄的遞歸.

#!/usr/bin/env python  
# 3.py  
# use UTF-8  
# Python 3.3.0  
  
# os.walk()的使用  
import os  
  
# 枚舉dirPath目錄下的所有文件  
  
def main():  
#begin  
    fileDir = "F:" + os.sep + "aaa"     # 查找F:\aaa 目錄下    
    for a in os.walk(fileDir):  
    #begin  
        print(a[0])  
        print(a[1])  
        print(a[2])  
    #end  
    os.system("pause")  
#end  
  
if __name__ == '__main__':  
#begin  
    main()  
#end  
  
  
# 輸出  
# F:\aaa  
# ['4']  
# ['1.txt', '2.txt', '3.txt']  
# F:\aaa\4  
# []  
# ['5.txt', '6.txt', '7.txt']

你還可以這樣,先打印目錄,再打印各個文件:

#!/usr/bin/env python  
# 2.py  
# use UTF-8  
# Python 3.3.0  
  
# os.walk()的使用  
import os  
  
# 枚舉dirPath目錄下的所有文件  
  
def main():  
#begin  
    fileDir = "F:" + os.sep + "aaa"     # 查找F:\aaa 目錄下    
    for root, dirs, files in os.walk(fileDir):  
    #begin  
        for dir in dirs:  
        #begin  
            print(os.path.join(root, dir))  
        #end  
        for file in files:  
        #begin  
            print(os.path.join(root, file))  
        #end  
    #end  
    os.system("pause")  
#end  
  
if __name__ == '__main__':  
#begin  
    main()  
#end  
  
  
# 輸出  
# F:\aaa\4  
# F:\aaa\1.txt  
# F:\aaa\2.txt  
# F:\aaa\3.txt  
# F:\aaa\4\5.txt  
# F:\aaa\4\6.txt  
# F:\aaa\4\7.txt

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章