2014-02-10 41 views
0

如何檢查某些目錄是否包含Python中的字母a,如果有,請將其刪除。這是我的代碼,使用shutil。它檢查是否一個目錄被命名爲a,如果它存在(和子目錄等)中刪除它,但它不會刪除一個文件夾命名爲a7刪除名稱中帶有某個字母的目錄

import shutil 

not_allowed = ["a", "b"] 

for x in not_allowed: 
    if x in not_allowed: 
     shutil.rmtree(x) 

我如何管理做這個?

+1

您應該先將文件夾名稱存儲在一個變量中。 –

回答

1
import shutil 

fileList = ["crap", "hest"] 

not_allowed = ["a", "b"] 

for x in fileList: 
    for y in not_allowed 
     if y in x: 
      shutil.rmtree(x) 
      continue 
2

再說說你的目錄名存儲在dirname

for x in not_allowed: 
    if x in dirname: 
     shutil.rmtree(dirname) 

再說,我會做這樣的:

if any(x in dirname for x in not_allowed): 
    shutil.rmtree(dirname) 
1
import os 
import shutil 

not_allowed = ["a", "b"] 

basedir = '/tmp/dir_to_search_in/' 

for d in os.listdir(basedir): 
    if os.path.isdir(d) and any(x in d for x in not_allowed): 
     shutil.rmtree(d) 

0

可實現了一些簡單的列表理解

paths = ['directory1','directory2','others'] 
forbid = ['j','d'] 

print [p for p in paths if filter(lambda x:x not in p,forbid) == forbid] 
['others'] 
相關問題