-
Hajipur, Bihar, 844101
Deleting files is an important part of file management in Python. Whether you are removing temporary files, logs, outdated data, or backups, Python provides built-in tools to delete files safely and efficiently. Understanding file deletion ensures that your programs clean up resources and maintain storage space effectively.
This tutorial covers deleting files using the os module, checking for existence, handling errors, and practical examples.
os Module to Delete FilesPython’s os module provides the remove() function to delete files:
import os
os.remove("example.txt")
example.txt – the file to delete
Throws a FileNotFoundError if the file does not exist
Before deleting a file, it’s safe to check if the file exists to prevent errors:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted successfully.")
else:
print("File not found.")
os.path.exists() – Returns True if the file exists
Prevents runtime errors when attempting to delete non-existent files
Using try-except ensures your program doesn’t crash if an error occurs:
import os
try:
os.remove("example.txt")
print("File deleted successfully.")
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("You do not have permission to delete this file.")
This method handles common errors like missing files or permission issues.
Pathlib ModulePython’s pathlib module (introduced in Python 3.4) provides an object-oriented approach to file management:
from pathlib import Path
file = Path("example.txt")
if file.exists():
file.unlink() # Deletes the file
print("File deleted successfully.")
else:
print("File does not exist.")
Path() – Represents the file path
unlink() – Deletes the file
This approach is cleaner and works well with modern Python projects.
You can delete multiple files programmatically:
import os
files = ["file1.txt", "file2.txt", "file3.txt"]
for file in files:
if os.path.exists(file):
os.remove(file)
print(f"{file} deleted.")
else:
print(f"{file} not found.")
This is useful for batch cleanup tasks.
Programs often generate temporary files that need to be removed after use:
import os
import tempfile
# Create a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False)
print("Temporary file created:", temp_file.name)
# Close and delete the temporary file
temp_file.close()
if os.path.exists(temp_file.name):
os.remove(temp_file.name)
print("Temporary file deleted.")
The tempfile module is ideal for temporary storage during program execution.
To delete all files in a folder, you can use os.listdir() combined with os.remove():
import os
folder = "my_folder"
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
if os.path.isfile(file_path):
os.remove(file_path)
print(f"{filename} deleted.")
Checks if each item is a file before deleting
Prevents accidentally deleting directories
Always check if the file exists before deletion
Use try-except blocks to handle errors gracefully
Avoid deleting critical system files
Backup important files before deletion
Use pathlib for modern, readable code
These practices prevent data loss and program errors.
Delete a single file safely:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted successfully.")
Delete a file using try-except:
import os
try:
os.remove("example.txt")
except FileNotFoundError:
print("File does not exist.")
Delete multiple files in a list:
files = ["file1.txt", "file2.txt"]
import os
for f in files:
if os.path.exists(f):
os.remove(f)
print(f"{f} deleted.")
Delete files in a folder:
import os
folder = "documents"
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
if os.path.isfile(file_path):
os.remove(file_path)
Delete temporary file:
import tempfile
import os
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.close()
os.remove(temp_file.name)
print("Temporary file deleted.")
Delete a file using pathlib:
from pathlib import Path
file = Path("example.txt")
if file.exists():
file.unlink()
Handle permission errors:
import os
try:
os.remove("protected_file.txt")
except PermissionError:
print("Cannot delete, permission denied.")
Delete all .txt files in a directory:
import os
folder = "texts"
for f in os.listdir(folder):
if f.endswith(".txt"):
os.remove(os.path.join(folder, f))
Check and delete file with logging:
import os
filename = "log.txt"
if os.path.exists(filename):
os.remove(filename)
print(f"{filename} has been deleted.")
else:
print(f"{filename} does not exist.")
Delete files created during runtime:
import tempfile
import os
file = tempfile.NamedTemporaryFile(delete=False)
file_name = file.name
file.close()
if os.path.exists(file_name):
os.remove(file_name)
print("Runtime file deleted.")
Deleting files in Python is straightforward but must be done carefully to avoid data loss. Key points:
Use os.remove() or pathlib.Path().unlink() to delete files
Check file existence using os.path.exists() before deletion
Use try-except blocks for error handling
Delete multiple files using loops for batch cleanup
Use the tempfile module for managing temporary files
Mastering file deletion ensures efficient resource management and prevents unnecessary clutter in your file system, which is essential for real-world Python applications like data management, automation, and temporary storage handling.
Q1. Write a Python program to delete a file named demo.txt using os.remove().
Q2. Write a Python program to delete a file only if it exists, using os.path.exists().
Q3. Write a Python program to delete a folder named temp only if it’s empty, using os.rmdir().
Q4. Write a Python program to use try/except to safely delete a file that might not exist.
Q5. Write a Python program to use a loop to delete all .bak files from a directory.
Q6. Write a Python program to use shutil.rmtree() to remove a folder with all its contents.
Q7. Write a Python program to define a function that deletes a file if it is found, and returns success or failure.
Q8. Write a Python program to remove a folder and handle permission errors using a try/except block.
Q9. Write a Python program to prompt the user to enter a file name and delete it if it exists.
Q10. Write a Python program to log a message when a file is deleted successfully (e.g., print "File deleted.").