To delete a file in Python, you can use the os.remove()
function from the os
module.
Deleting a File
import os
file_path = "filename.txt"
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} has been deleted.")
else:
print("The file does not exist.")
os.remove(file_path)
: Deletes the file at the specified path.
os.path.exists(file_path)
: Checks if the file exists before attempting to delete it, which helps avoid errors.
Using pathlib
(Python 3.4+)
Alternatively, you can use the Path
class from pathlib
for a more object-oriented approach.
from pathlib import Path
file_path = Path("filename.txt")
if file_path.exists():
file_path.unlink() # Deletes the file
print(f"{file_path} has been deleted.")
else:
print("The file does not exist.")