0
DirA
  file1.txt
  file2.conf
  DirB
      file3.txt
      file4.sh
      file5.sh
      DirC
          file6.bat
          file7.txt

In above example dir I need to perform recursive delete with glob pattern.

pattern = ['*,txt','*.sh']

Using the above pattern I need to delete all the files with *.txt and *.sh formats in all the directory

0

3 Answers 3

1
import os, glob

pattern = ['*.txt', '*.sh']

for p in pattern:
    [os.remove(x) for x in glob.iglob('DirA/**/' + p, recursive=True)]

If you want you can use list comprehensions to do this task. Cya!

Sign up to request clarification or add additional context in comments.

Comments

1
import os
import glob

for filename in glob.iglob('DirA/**/*.txt', recursive=True):
    os.remove(filename)
for filename in glob.iglob('DirA/**/*.sh', recursive=True):
    os.remove(filename)

This should work to delete all txt and sh files in the directory recursively.

Or if you want to specify an array with patterns:

import os
import glob


def removeAll(pathToDir, patterns):
    for pattern in patterns:
        for filename in glob.iglob(pathToDir + '/**/' + pattern, recursive=True):
            os.remove(filename)


patterns = ['*.txt', '*.sh']

removeAll('DirA', patterns)

Comments

1

You can use os.walk instead so that you only need to traverse the directories once. With glob you would have to traverse twice since you have two patterns to look for.

import os
for root, _, files in os.walk('DirA'):
    for file in files:
        if any(file.endswith(ext) for ext in pattern):
            os.remove(os.path.join(root, file))

4 Comments

Instead of .endswith can we use glob pattern? Because the patterns are passed as a parameter
glob pattern is a simplified version of regex. You can test the file name with a regex pattern if you have a more complex file pattern that can't be tested with the endswith method; otherwise the endswith method is more efficient.
Assuming none of your files have extraneous . you could also use if file.split('.')[1] in patterns. This will allow you to compare to patterns list
I've updated my answer to make use of the pattern list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.