简体   繁体   中英

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

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!

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM