Deleting files and directories is an essential operation for managing storage and cleaning up unnecessary data. Python's os
and shutil
modules provide methods to safely remove files and folders.
os.remove()
, also deletes a file.import os
os.remove('sample.txt')
import os
try:
os.remove('sample.txt')
except FileNotFoundError:
print("File not found.")
import os
os.unlink('sample.txt')
import os
os.rmdir('empty_folder')
import shutil
shutil.rmtree('folder_with_files')
import os
file_path = 'sample.txt'
if os.path.exists(file_path):
os.remove(file_path)
else:
print("File does not exist.")
import os
dir_path = 'old_folder'
if os.path.isdir(dir_path):
os.rmdir(dir_path)
else:
print("Directory does not exist or is not empty.")
import os
folder = 'logs'
for filename in os.listdir(folder):
if filename.endswith('.log'):
os.remove(os.path.join(folder, filename))
import shutil
try:
shutil.rmtree('temp_folder')
except FileNotFoundError:
print("Folder not found.")
from pathlib import Path
file = Path('sample.txt')
if file.exists():
file.unlink()