Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to remove swap files using Python?
Swap files and temporary files are common byproducts of text editors such as Vim, Emacs or modern IDEs. These files?often with extensions like .swp, .swo, .tmp or .bak?are used to store session data or backup content temporarily. While useful during editing sessions, they can clutter project directories or interfere with version control systems if not cleaned up.
In this article, we explore how to leverage Python to automatically find and delete these unwanted swap files from our workspace.
Using os.walk() for Recursive Deletion
The os.walk() method recursively traverses directories and removes files that match common swap file extensions ?
import os
def remove_swap_files(directory, extensions=('.swp', '.swo', '.tmp', '.bak')):
"""Remove swap files recursively from directory"""
count = 0
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(extensions):
file_path = os.path.join(root, file)
print(f"Removing: {file_path}")
try:
os.remove(file_path)
count += 1
except OSError as e:
print(f"Error removing {file_path}: {e}")
print(f"Removed {count} swap files")
# Example usage (create test files first)
test_dir = "test_swap_cleanup"
os.makedirs(test_dir, exist_ok=True)
# Create sample swap files
with open(f"{test_dir}/test.swp", "w") as f:
f.write("swap file")
with open(f"{test_dir}/backup.bak", "w") as f:
f.write("backup file")
remove_swap_files(test_dir)
Removing: test_swap_cleanup/test.swp Removing: test_swap_cleanup/backup.bak Removed 2 swap files
Note: This method is ideal for recursively scanning entire projects for swap files.
Using glob for Pattern Matching
The glob module allows pattern matching with wildcard syntax. Use ** for recursive search ?
import glob
import os
def remove_with_glob(directory):
"""Remove swap files using glob pattern matching"""
patterns = ['**/*.swp', '**/*.swo', '**/*.tmp', '**/*.bak']
count = 0
for pattern in patterns:
full_pattern = os.path.join(directory, pattern)
for file_path in glob.glob(full_pattern, recursive=True):
print(f"Removing: {file_path}")
try:
os.remove(file_path)
count += 1
except OSError as e:
print(f"Error: {e}")
print(f"Total files removed: {count}")
# Create test files
test_dir = "glob_test"
os.makedirs(f"{test_dir}/subdir", exist_ok=True)
with open(f"{test_dir}/file.tmp", "w") as f:
f.write("temp")
with open(f"{test_dir}/subdir/vim.swp", "w") as f:
f.write("vim swap")
remove_with_glob(test_dir)
Removing: glob_test/file.tmp Removing: glob_test/subdir/vim.swp Total files removed: 2
Using pathlib Module
Python's pathlib provides a modern object-oriented interface. Use rglob() for recursive pattern matching ?
from pathlib import Path
def remove_with_pathlib(directory):
"""Remove swap files using pathlib (Python 3.5+)"""
path = Path(directory)
extensions = ('.swp', '.swo', '.tmp', '.bak')
count = 0
for file in path.rglob('*'):
if file.suffix in extensions and file.is_file():
print(f"Removing: {file}")
try:
file.unlink()
count += 1
except OSError as e:
print(f"Error: {e}")
print(f"Files removed: {count}")
# Create test structure
test_path = Path("pathlib_test")
test_path.mkdir(exist_ok=True)
(test_path / "nested").mkdir(exist_ok=True)
# Create sample files
(test_path / "main.bak").write_text("backup")
(test_path / "nested" / "session.swp").write_text("swap")
remove_with_pathlib(test_path)
Removing: pathlib_test/main.bak Removing: pathlib_test/nested/session.swp Files removed: 2
Adding a Dry Run Option
Implement a dry run mode to preview deletions without actually removing files ?
import os
def clean_swap_files(directory, extensions=('.swp', '.tmp', '.bak'), dry_run=True):
"""Clean swap files with optional dry run mode"""
count = 0
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(extensions):
file_path = os.path.join(root, file)
if dry_run:
print(f"[DRY RUN] Would remove: {file_path}")
else:
print(f"Removing: {file_path}")
try:
os.remove(file_path)
except OSError as e:
print(f"Error: {e}")
count += 1
action = "Would remove" if dry_run else "Removed"
print(f"{action} {count} swap files")
# Create test files
test_dir = "dry_run_test"
os.makedirs(test_dir, exist_ok=True)
with open(f"{test_dir}/test.swp", "w") as f:
f.write("test swap")
# First run dry run
clean_swap_files(test_dir, dry_run=True)
print("\n" + "="*40 + "\n")
# Then actual cleanup
clean_swap_files(test_dir, dry_run=False)
[DRY RUN] Would remove: dry_run_test/test.swp Would remove 1 swap files ======================================== Removing: dry_run_test/test.swp Removed 1 swap files
Comparison of Methods
| Method | Python Version | Best For | Performance |
|---|---|---|---|
os.walk() |
All versions | Simple recursive cleanup | Fast |
glob |
All versions | Pattern-based filtering | Medium |
pathlib |
3.5+ | Modern object-oriented approach | Fast |
Conclusion
Use os.walk() for simple recursive cleanup, glob for pattern matching, or pathlib for modern Python projects. Always implement dry run mode to prevent accidental deletions of important files.
