Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
In Python, you can use the os
module to remove files and directories. The os.remove()
function is used to remove files, and the os.rmdir()
function is used to remove empty directories. If you need to remove a directory and its contents, you can use the shutil.rmtree()
function from the shutil
module.
Here's how to use these functions:
import os file_path = 'path/to/your/file.txt' # Remove the file if os.path.isfile(file_path): os.remove(file_path) else: print(f"{file_path} not found.")
import os directory_path = 'path/to/your/directory' # Remove the empty directory if os.path.isdir(directory_path): try: os.rmdir(directory_path) except OSError: print(f"{directory_path} is not empty.") else: print(f"{directory_path} not found.")
import shutil directory_path = 'path/to/your/directory' # Remove the directory and its contents if os.path.isdir(directory_path): shutil.rmtree(directory_path) else: print(f"{directory_path} not found.")
In the examples above, the os.path.isfile()
and os.path.isdir()
functions are used to check if a given path refers to a file or a directory, respectively. This helps to ensure that you are removing the correct type of object and provides a chance to display an error message if the specified path is not found.
Deleting a file in Python:
os.remove()
function to delete a file.import os file_path = 'example.txt' # Delete a file os.remove(file_path)
Remove file using os.remove() in Python:
os.remove()
function.import os file_path = 'example.txt' # Remove a file os.remove(file_path)
How to delete a directory in Python:
os.rmdir()
function to delete an empty directory.import os directory_path = 'example_directory' # Delete an empty directory os.rmdir(directory_path)
Python delete file if exists:
import os file_path = 'example.txt' # Delete file if it exists if os.path.exists(file_path): os.remove(file_path)
Deleting multiple files in Python:
import os files_to_delete = ['file1.txt', 'file2.txt', 'file3.txt'] # Delete multiple files for file in files_to_delete: os.remove(file)
Remove directory and its contents in Python:
shutil.rmtree()
to remove a directory and its contents.import shutil directory_path = 'example_directory' # Remove directory and its contents shutil.rmtree(directory_path)
Python shutil.rmtree() for removing directories:
shutil.rmtree()
to remove directories and their contents.import shutil directory_path = 'example_directory' # Remove directory and its contents shutil.rmtree(directory_path)
Deleting files based on a condition in Python:
import os directory_path = 'files_to_delete' # Delete files based on a condition for file in os.listdir(directory_path): if file.endswith('.txt'): file_path = os.path.join(directory_path, file) os.remove(file_path)
Safely remove a file in Python:
import os file_path = 'example.txt' # Safely remove a file try: os.remove(file_path) except FileNotFoundError: print(f"File not found: {file_path}")
Python remove file and handle exceptions:
import os file_path = 'example.txt' # Remove a file and handle exceptions try: os.remove(file_path) except OSError as e: print(f"Error removing file: {e}")
Deleting empty directories in Python:
os.rmdir()
.import os directory_path = 'empty_directory' # Delete empty directory os.rmdir(directory_path)
Recursive file and directory removal in Python:
import shutil directory_path = 'example_directory' # Recursive removal of files and directories shutil.rmtree(directory_path)
Remove specific file type in Python:
import os directory_path = 'files_to_delete' # Remove specific file type for file in os.listdir(directory_path): if file.endswith('.log'): file_path = os.path.join(directory_path, file) os.remove(file_path)
Deleting read-only files in Python:
import os file_path = 'read_only_file.txt' # Remove read-only attribute and delete file os.chmod(file_path, 0o777) # Change file mode to allow deletion os.remove(file_path)
Permanently delete files in Python:
shutil.disk_usage()
to check available space before permanent deletion.import os import shutil file_path = 'file_to_delete.txt' # Permanently delete file if enough space is available free_space = shutil.disk_usage('/').free if os.path.exists(file_path) and os.path.getsize(file_path) < free_space: os.remove(file_path)
Python delete file with wildcard:
glob
to delete files matching a wildcard pattern.import glob import os files_to_delete = glob.glob('files_to_delete/*.txt') # Delete files with wildcard for file in files_to_delete: os.remove(file)
Deleting files older than a certain date in Python:
import os import datetime directory_path = 'files_to_delete' threshold_date = datetime.datetime(2022, 1, 1) # Delete files older than the specified date for file in os.listdir(directory_path): file_path = os.path.join(directory_path, file) last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(file_path)) if last_modified < threshold_date: os.remove(file_path)
Python remove directory and its contents:
shutil.rmtree()
.import shutil directory_path = 'example_directory' # Remove directory and its contents shutil.rmtree(directory_path)
Secure file and directory deletion in Python:
import os import send2trash # Install with pip install send2trash file_path = 'file_to_delete.txt' directory_path = 'directory_to_delete' # Securely delete file send2trash.send2trash(file_path) # Securely delete directory send2trash.send2trash(directory_path)