How can I delete a file or folder in Python?
To delete a file or folder in Python, you can use the os
module and call the os.remove()
function to delete a file, or the shutil.rmtree()
function to delete a folder and all its contents. Here is an example of how to use these functions:
import os
import shutil
# Delete a file
os.remove("path/to/file.txt")
# Delete a folder and all its contents
shutil.rmtree("path/to/folder")
Watch a video course
Python - The Practical Guide
Note that these functions will raise an error if the file or folder does not exist, so you may want to include some error handling to catch this case.
import os
import shutil
# Delete a file
try:
os.remove("path/to/file.txt")
except FileNotFoundError:
print("File not found")
# Delete a folder and all its contents
try:
shutil.rmtree("path/to/folder")
except FileNotFoundError:
print("Folder not found")