2011-06-02 63 views
38

全部,在Python中查找空目錄

什麼是在刪除目錄之前查看目錄中是否有數據的最佳方法?我正在瀏覽幾個頁面,使用wget來查找一些圖片,當然,每個頁面上都沒有圖像,但該目錄仍然被創建。

dir = 'Files\\%s' % (directory) 
os.mkdir(dir) 
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir, i[1]) 
os.system(cmd) 
if not os.path.isdir(dir): 
    os.rmdir(dir) 

我想測試一下文件是否在創建後刪除目錄。如果什麼都沒有......刪除它。

感謝, 亞當

+0

定義「空」。如果有子目錄呢?他們應該檢查數據嗎?如果他們沒有數據,他們是否也應該被刪除? – kwatford 2011-06-02 13:57:33

+0

在這種情況下,我沒有任何子目錄只是一個文件夾,它可能有或沒有照片。 – aeupinhere 2011-06-02 14:04:42

+3

請不要使用os.system來調用wget。使用子流程.Popen – 2011-06-02 14:43:08

回答

17

嘗試:

if not os.listdir(dir): 
    print "Empty" 

if os.listdir(dir) == []: 
    print "Empty" 
47
import os 

if not os.listdir(dir): 
    os.rmdir(dir) 

LBYL風格。
for EAFP,參見mouad的回答。

1

如果該目錄存在,以及是否有目錄中的內容,如果你也查了一下......是這樣的:

if os.path.isdir(dir) and len(os.listdir(dir)) == 0: 
    os.rmdir(dir) 
41

我將與EAFP去像這樣:

try: 
    os.rmdir(dir) 
except OSError as ex: 
    if ex.errno == errno.ENOTEMPTY: 
     print "directory not empty" 

注意:os.rmdir不要刪除非空的目錄。

+2

+1:簡單。直接。它將全部**的棘手決策委託給它所屬的操作系統。 – 2011-06-02 13:56:54

+1

請注意,此函數會靜默地刪除您可能想要報告的所有其他錯誤(例如'EACCESS')。請注意,天真地解決這個問題可能會導致爲非空目錄報告錯誤,您可能會忽略它。不像看起來那麼簡單:-) – 2014-01-08 16:51:16

+2

'else:raise'呢? – spectras 2015-09-07 17:05:41

1

如果已經創建的空目錄,你可以把這個腳本在你的外部目錄並運行它:

import os 

def _visit(arg, dirname, names): 
    if not names: 
     print 'Remove %s' % dirname 
     os.rmdir(dirname) 

def run(outer_dir): 
    os.path.walk(outer_dir, _visit, 0) 

if __name__ == '__main__': 
    outer_dir = os.path.dirname(__file__) 
    run(outer_dir) 
    os.system('pause') 
-1
import os 
import tempfile 

root = tempfile.gettempdir() 
EMPTYDIRS = [] 

for path, subdirs, files in os.walk(r'' + root): 
    if len(files) == 0 and len(subdirs) == 0: 
     EMPTYDIRS.append(path) 

for e in EMPTYDIRS: 
    print e 
1

這現在可以在Python3更有效地完成,因爲沒有必要建立一個目錄內容清單,看看它是否爲空:

import os 

def is_dir_empty(path): 
    return next(os.scandir(path), None) is None