Python Delete Files
To delete files in Python, we use the built-in os module which provides functions for interacting with the operating system.
Import os Module
import os1. Delete a File
import os
if os.path.exists("demo.txt"):
os.remove("demo.txt")
print("File deleted successfully.")
else:
print("File does not exist.")Output (if file exists):
File deleted successfully.Explanation:
os.path.exists()checks if the file exists to prevent errors.os.remove()deletes the file.
2. What if File Doesn’t Exist?
import os
os.remove("nofile.txt")Output (Error):
FileNotFoundError: [Errno 2] No such file or directory: 'nofile.txt'Explanation:
Always check if a file exists before trying to delete it, or use try/except.
3. Handle Deletion Safely with Try-Except
import os
try:
os.remove("demo.txt")
print("File deleted.")
except FileNotFoundError:
print("The file was not found.")
except PermissionError:
print("Permission denied.")Output:
The file was not found.Explanation:
Use try/except to handle common errors like missing files or permission issues.
4. Delete All .txt Files in a Folder
import os
for file in os.listdir():
if file.endswith(".txt"):
os.remove(file)
print(f"Deleted: {file}")Sample Output:
Deleted: test1.txt
Deleted: notes.txtExplanation:
os.listdir()lists all files in the current directory.os.remove()deletes files that match a pattern.
Real-World Use Case: Cleanup Temporary Files
import os
def cleanup_temp_files(folder_path):
for file in os.listdir(folder_path):
if file.endswith(".tmp"):
os.remove(os.path.join(folder_path, file))
print(f"Deleted temp file: {file}")
cleanup_temp_files(".")Explanation:
Helps keep your project folder clean by removing .tmp files created during processing.
Summary Table
| Function | Description |
|---|---|
os.remove(path) | Deletes a file |
os.path.exists(path) | Checks if the file exists |
os.listdir() | Lists files in a directory |
try/except | Handles missing file or permissions |