2016-01-20 89 views
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) 
+0

這裏只是拋出一個猜測後,立即刪除目錄:在最後一行,如果你碰巧,而不是試圖什麼,刪除根,將它追加到列表中,然後在所有循環之後,刪除該列表中的所有目錄? –

+1

也許與問題無關,但更好的使用'os.path.join'來形成路徑(例如'os.walk'調用內)。 – errikos

回答

4

使用insted的功能

os.removedirs(path) 

這將刪除目錄,直到父目錄是不是空的。

0

理想情況下,你應該刪除文件,而不是做兩遍與os.walk

import sys 
import os 

for dir, subdirs, files in os.walk(sys.argv[1], topdown=False): 
    for name in files: 
     if not(name.endswith(".pdf")): 
      os.remove(os.path.join(dir, name)) 
     if len(os.listdir(dir)) == 0: #check whether the directory is now empty after deletions, and if so, remove it 
      os.rmdir(dir)