ArockiaRaj
ArockiaRaj

Reputation: 608

How to perform recursive delete using glob pattern in a directory using python?

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

Upvotes: 0

Views: 2052

Answers (3)

blhsing
blhsing

Reputation: 106543

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))

Upvotes: 1

Luis Alves
Luis Alves

Reputation: 194

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!

Upvotes: 1

vividpk21
vividpk21

Reputation: 384

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)

Upvotes: 1

Related Questions