删除名称中包含特定字母的目录

时间:2014-02-10 13:01:14

标签: python python-2.7

如何检查某些目录是否包含Python中的字母 a ,如果是,则删除它们。这是我使用shutil的代码。它检查一个目录是否被命名为a并删除它(如果它存在(和子目录等))但它不删除名为a7的文件夹:

import shutil

not_allowed = ["a", "b"]

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

我该如何设法做到这一点?

4 个答案:

答案 0 :(得分: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 :(得分: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 :(得分: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)

答案 3 :(得分: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']