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



How can I delete multiple files in a directory in Python? __del__: Questions

How can I delete multiple files in a directory in Python? __delete__: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method