How to Recover Deleted .txt Files from a Backup in Python
A Python function that searches a backup directory recursively and copies all .txt files to a destination folder, printing each recovered file name and a total count.
Python code
24 linesimport os
import shutil
from pathlib import Path
def recover_deleted_txt_files(source_backup_dir: str, destination_dir: str) -> None:
"""Recover .txt files from backup directory."""
backup_path = Path(source_backup_dir)
dest_path = Path(destination_dir)
dest_path.mkdir(parents=True, exist_ok=True)
if not backup_path.exists():
print(f"Backup directory '{source_backup_dir}' does not exist.")
return
recovered = 0
for txt_file in backup_path.rglob("*.txt"):
shutil.copy2(txt_file, dest_path / txt_file.name)
recovered += 1
print(f"Recovered: {txt_file.name}")
print(f"\nTotal recovered: {recovered} text file(s) to '{destination_dir}'")
if __name__ == "__main__":
recover_deleted_txt_files("test_backup", "recovered_files")
Output
Recovered: notes.txt
Recovered: report.txt
Recovered: config.txt
Total recovered: 3 text file(s) to 'recovered_files'
How it works
The script uses pathlib.Path.rglob('*.txt') to recursively find all text files in the backup directory. shutil.copy2 copies each file while preserving metadata (timestamps). The destination folder is created automatically with mkdir(parents=True, exist_ok=True). The function prints each recovered file and a final count, making the process transparent. This approach is safe—it only reads from the backup and never modifies the original files.
Common mistakes
- Forgetting to create the destination directory before copying files.
- Using `glob` instead of `rglob` to miss files in subdirectories.
- Overwriting existing files in the destination without checking.
Variations
- Use `pathlib.Path.copy()` if you want to copy without metadata (Python 3.14+).
- Add a `dry_run=True` parameter to simulate without writing.
Real-world use cases
- Restoring user documents from a daily backup drive after accidental deletion.
- Recovering configuration files from a project's backup folder after a reset.
- Selectively restoring only text-based logs from a compressed backup archive.
Sponsored
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.