Automating File Backups
Backup strategy (simple and effective)
- choose what to back up
- create timestamped archives
- store backups in a separate location
Zip a folder
backup_zip.py
from __future__ import annotations
from datetime import datetime
from pathlib import Path
import shutil
def backup_folder(folder: Path, out_dir: Path) -> Path:
folder = folder.resolve()
out_dir.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
archive_base = out_dir / f"{folder.name}_{stamp}"
# creates archive_base.zip
archive_path = shutil.make_archive(str(archive_base), "zip", root_dir=str(folder))
return Path(archive_path)
p = backup_folder(Path("./demo"), Path("./backups"))
print("created", p)backup_zip.py
from __future__ import annotations
from datetime import datetime
from pathlib import Path
import shutil
def backup_folder(folder: Path, out_dir: Path) -> Path:
folder = folder.resolve()
out_dir.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
archive_base = out_dir / f"{folder.name}_{stamp}"
# creates archive_base.zip
archive_path = shutil.make_archive(str(archive_base), "zip", root_dir=str(folder))
return Path(archive_path)
p = backup_folder(Path("./demo"), Path("./backups"))
print("created", p)Tips
- keep multiple backups
- test restore occasionally
- don’t back up into the same folder you’re archiving
Visualize it
A backup script moves files from the source folder to a safe destination in a few clear steps.
flowchart LR
A["Scan source folder"] --> B["Select files to back up"]
B --> C["Compress into zip archive"]
C --> D["Copy to backup destination"]
🧪 Try It Yourself
Exercise 1 – List Files with os.listdir
Exercise 2 – Join Paths with os.path.join
Exercise 3 – Write and Read a File
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
