- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How to delete all files in a directory with Python?
You can delete a single file or a single empty folder with functions in the os module.
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 and recreate it as follows:
>>> import shutil >>> shutil.rmtree('my_folder') >>> import os >>> os.makedirs('my_folder')
You can also recursively delete the files using os.walk().
import os, re, os.path mypath = "my_folder" for root, dirs, files in os.walk(mypath): for file in files: os.remove(os.path.join(root, file))
The directory tree will be intact if above method is used.
- Related Articles
- How to delete multiple files in a directory in Python?
- Java program to delete all the files in a directory recursively (only files)
- How to find all files in a directory with extension .txt in Python?
- How do I list all files of a directory in Python?
- How to list all files in a directory using Java?
- How to unzip all zipped files in a Linux directory?
- How to delete a Python directory effectively?
- How to perform grep operation on all files in a directory?
- How to rename multiple files in a directory in Python?
- What is the best way to run all Python files in a directory?
- How to read data from all files in a directory using Java?
- How to list all files (only) from a directory using Java?
- Java program to List all files in a directory recursively
- Golang program to get all files present in a directory
- How to get all the files, sub files and their size inside a directory in C#?