Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Easy Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Python code

24 lines
Python 3.9+
import 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

stdout
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

  1. Use `pathlib.Path.copy()` if you want to copy without metadata (Python 3.14+).
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.