Change language

How can I delete multiple files in a directory in Python?

| | |

You can delete one file or one empty folder with functions in the os module.

Example

For example, if you want to delete the file my_file.txt,

""" import os""" os.remove (’my_file.txt’) 

The os.remove argument must be an absolute or relative path.




To delete multiple files, simply scroll through the file list and use the above function. If you want to delete a folder containing all the files you want to delete, you can delete the folder as follows:

""" import shutil""" shutil.rmtree (’my_folder’) 

You can also use regular expressions to remove files that match a pattern. For example,

 import os, re, os.path pattern = "^ your_regex_here $" mypath = "my_folder" for root, dirs, files in os.walk (mypath): for file in filter (lambda x: re.match (pattern, x), files): os.remove ( os.path.join ( (root, file))