2
我有麻煩找到並刪除空文件夾我的室內用python腳本..的Python:刪除空文件夾recusively
我有一些目錄與文件的多個O少這樣的:
A/
--B/
----a.txt
----b.pdf
--C/
----d.pdf
我試圖做的是刪除所有不是pdf的文件,然後刪除所有空文件夾。我可以刪除我想要的文件,但是我無法得到空目錄..我做錯了什麼?
os.chdir(path+"/"+name+"/Test Data/Checklists")
pprint("Current path: "+ os.getcwd())
for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists"):
for name in files:
if not(name.endswith(".pdf")):
os.remove(os.path.join(root, name))
pprint("Deletting empty folders..")
pprint("Current path: "+ os.getcwd())
for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists", topdown=False):
if not dirs and not files:
os.rmdir(root)
這裏只是拋出一個猜測後,立即刪除目錄:在最後一行,如果你碰巧,而不是試圖什麼,刪除根,將它追加到列表中,然後在所有循環之後,刪除該列表中的所有目錄? –
也許與問題無關,但更好的使用'os.path.join'來形成路徑(例如'os.walk'調用內)。 – errikos