Python allows you to delete files using the os module. Before deleting a file, it is recommended to check whether the file exists.
Import the os Module
Example
import os
Delete a File
The remove() method deletes a file.
Syntax
os.remove("file_name")
Example
import os
os.remove("sample.txt")
Check if a File Exists Before Deleting
Example
import os
if os.path.exists("sample.txt"):
os.remove("sample.txt")
print("File deleted")
else:
print("File does not exist")
Output:
File deleted
Delete an Empty Folder
The rmdir() method deletes an empty folder.
Syntax
os.rmdir("folder_name")
Example
import os
os.rmdir("myfolder")
Check if a Folder Exists
Example
import os
if os.path.exists("myfolder"):
os.rmdir("myfolder")
print("Folder deleted")
else:
print("Folder does not exist")
Output:
Folder deleted
Handle File Deletion Errors
Example
import os
try:
os.remove("sample.txt")
print("File deleted")
except FileNotFoundError:
print("File not found")
Output:
File not found
Delete File Using Path
Example
import os
file_path = "files/sample.txt"
if os.path.exists(file_path):
os.remove(file_path)
print("File deleted")
Output:
File deleted
Summary
- Use the
osmodule to delete files and folders. os.remove()deletes a file.os.rmdir()deletes an empty folder.- Always check file existence before deleting.
- Use
try...exceptto handle deletion errors. - Deleting a file permanently removes it from the system.