Deleting Files and Directories in Python

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.

Key Concepts

10 Python Examples for Deleting Files and Directories

Example 1: Delete a single file

import os
os.remove('sample.txt')

Example 2: Delete a file with error handling

import os
try:
    os.remove('sample.txt')
except FileNotFoundError:
    print("File not found.")

Example 3: Delete a file using os.unlink()

import os
os.unlink('sample.txt')

Example 4: Remove an empty directory

import os
os.rmdir('empty_folder')

Example 5: Remove a directory and all contents recursively

import shutil
shutil.rmtree('folder_with_files')

Example 6: Check if file exists before deleting

import os
file_path = 'sample.txt'
if os.path.exists(file_path):
    os.remove(file_path)
else:
    print("File does not exist.")

Example 7: Check if directory exists before removing

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.")

Example 8: Delete files with specific extension in a directory

import os
folder = 'logs'
for filename in os.listdir(folder):
    if filename.endswith('.log'):
        os.remove(os.path.join(folder, filename))

Example 9: Safe deletion with try-except for directories

import shutil
try:
    shutil.rmtree('temp_folder')
except FileNotFoundError:
    print("Folder not found.")

Example 10: Delete a file using pathlib

from pathlib import Path
file = Path('sample.txt')
if file.exists():
    file.unlink()