How to Delete a File or Folder in Python?
To delete a file or folder in Python, you can use the os
module.
Here’s an example of how to delete a file:
import os
# specify the file path
file_path = '/path/to/file'
# check if the file exists
if os.path.exists(file_path):
# delete the file
os.remove(file_path)
print("File deleted successfully")
else:
print("File not found")
And here’s an example of how to delete a folder:
import os
# specify the folder path
folder_path = '/path/to/folder'
# check if the folder exists
if os.path.exists(folder_path):
# delete the folder
os.rmdir(folder_path)
print("Folder deleted successfully")
else:
print("Folder not found")
Note that the os.rmdir()
function only works if the folder is empty. If the folder contains files or other folders, you will need to use shutil.rmtree()
instead. This function will delete the folder and all its contents:
import shutil
# specify the folder path
folder_path = '/path/to/folder'
# check if the folder exists
if os.path.exists(folder_path):
# delete the folder and all its contents
shutil.rmtree(folder_path)
print("Folder deleted successfully")
else:
print("Folder not found")
Make sure to use caution when deleting files and folders, as they cannot be easily recovered once they are deleted.