qu4ntum
qu4ntum

Reputation: 329

Remove directories with a certain letter in their names

How do I check if some directories include for example the letter a in Python, and delete them if so. This is my code using shutil. It checks to see if a directory is named a and removes it if it exists (and the sub-directories, etc.) but it doesn't delete a folder named a7:

import shutil

not_allowed = ["a", "b"]

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

How do I manage to do this?

Upvotes: 0

Views: 78

Answers (4)

wim
wim

Reputation: 362458

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)

Upvotes: 1

markcial
markcial

Reputation: 9323

can be achieved with some simple list comprehension

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

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

Upvotes: 0

Svend Feldt
Svend Feldt

Reputation: 778

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 

Upvotes: 1

Ricardo Cárdenes
Ricardo Cárdenes

Reputation: 9172

Say that your directory name is stored in dirname:

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

Then again, I'd do it like this:

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

Upvotes: 2

Related Questions