Python基础教程 os.walk()方法
生活随笔
收集整理的這篇文章主要介紹了
Python基础教程 os.walk()方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
os.walk方法,主要用來遍歷一個目錄內(nèi)各個子目錄和子文件。
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循環(huán)自動完成遞歸枚舉
例如:
F:\aaa 目錄是這樣的文件目錄結構
F:\aaa
|--------1.txt
|--------2.txt
|--------3.txt
|--------4
? |-------5.txt
? |-------6.txt
? |-------7.txt
分別打印各個參數(shù)的實際值
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' #!/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循環(huán)即可完成目錄的遞歸.
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' #!/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']你還可以這樣,先打印目錄,再打印各個文件
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' #!/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總結
以上是生活随笔為你收集整理的Python基础教程 os.walk()方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python的Super方法
- 下一篇: Python引用模块和查找模块路径