Restore sqlite from latest backup file in Python
This script finds the most recently modified backup file in a directory and restores it to the main database path, then verifies the restored data.
Python code
39 linesimport sqlite3
import glob
import os
import shutil
def restore_latest_backup(db_path, backup_dir):
backups = sorted(glob.glob(os.path.join(backup_dir, "*.db")), key=os.path.getmtime)
if not backups:
raise FileNotFoundError("No backup files found")
latest = backups[-1]
shutil.copy2(latest, db_path)
return latest
if __name__ == "__main__":
backup_dir = "backups"
os.makedirs(backup_dir, exist_ok=True)
# Create sample backups
for name in ["old.db", "mid.db", "newest.db"]:
path = os.path.join(backup_dir, name)
conn = sqlite3.connect(path)
conn.execute("CREATE TABLE data (value TEXT)")
conn.execute("INSERT INTO data VALUES (?)", (name,))
conn.commit()
conn.close()
# Restore latest backup
db_path = "restored.db"
restored_from = restore_latest_backup(db_path, backup_dir)
print(f"Restored from: {restored_from}")
conn = sqlite3.connect(db_path)
value = conn.execute("SELECT value FROM data").fetchone()[0]
print(f"Restored value: {value}")
conn.close()
os.remove(db_path)
for f in glob.glob(os.path.join(backup_dir, "*.db")):
os.remove(f)
Output
Restored from: backups/newest.db
Restored value: newest.db
How it works
The script uses glob.glob to find all .db files in the backup directory and sorts them by modification time using os.path.getmtime, so the last item is the newest backup. shutil.copy2 copies the file while preserving metadata. After restoring, the script connects to the database to verify the data and cleans up temporary files. Using os.makedirs ensures the backup directory exists, and the if __name__ == '__main__' guard allows the function to be imported without side effects.
Common mistakes
- Forgetting to sort by modification time, which may pick an arbitrary backup.
- Not handling the case where no backup files exist, causing an IndexError.
- Overwriting the current database without a backup of the current state first.
- Using `shutil.copy` instead of `shutil.copy2`, losing metadata like timestamps.
Variations
- Use `pathlib.Path.glob` and `stat().st_mtime` for a more modern approach.
- Add an argument parser to pass paths via command-line arguments.
Real-world use cases
- Automated nightly jobs that restore the latest snapshot before processing data.
- Disaster recovery scripts that bring a development environment back to a known good state.
- CI pipelines that restore a test database from the most recent backup before running tests.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- 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
Keep learning
Related tutorials and quizzes for this topic.