os.walk() 遍歷目錄下的文件夾和文件


os.walk(toptopdown=Trueonerror=Nonefollowlinks=False)

 

top:頂級目錄

os.walk()返回一個三元tupple(dirpath, dirnames, filenames)的生成器,其中dirpath是一個string,代表目錄的路徑,dirnames是一個list,包含了dirpath下所有子目錄的名字,但不包含上級目錄和本目錄('..'與'.')。filenames是一個list,包含了非目錄文件的名字。這些名字不包含路徑信息,如果需要得到全路徑,需要使用os.path.join(dirpath, name).

 

注意:生成器不能直接進行賦值解包,需用for、next等迭代工具產生元組或列表序列后進行解包賦值

 

手動解包賦值:

root,dirs,files = next(os.walk(r'd:\vb'))

 

for自動解包用法:

import os
for root, dirs, files in os.walk(r'd:\vb', topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM