- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to delete multiple files in a directory in Python?
You can delete a single file or a single empty folder with functions in the os module.
Example
For example, if you want to delete a file my_file.txt,
>>> import os >>> os.remove('my_file.txt')
The argument to os.remove must be absolute or relative path.
To delete multiple files, just loop over your list of files and use the above function. If you want to delete a folder containing all files you want to remove, you can remove the folder as follows:
>>> import shutil >>> shutil.rmtree('my_folder')
Example
You can also use regex to delete the files matching 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))
Advertisements
To Continue Learning Please Login
Login with Google