Keeping your data safe is one of the most important tasks for anyone working with technology. Losing important files due to system failures or accidental deletions can be catastrophic. Learning how to automate file backups with Python is an excellent way to protect your work. Python provides all the necessary tools to create scripts that make copies automatically without any manual effort, turning a tedious repetitive task into an invisible, efficient background process.
Why automate backups?
Manual backups fail for a simple reason: human memory. We forget to copy that important folder after a long workday, and manually selecting files, compressing, and moving to an external drive wastes precious time. An automated script works 24 hours a day. You can define specific rules, like copying only text files or photos, avoiding wasting disk space. To run this automatically on a schedule, see running system commands with Python.
Essential libraries
No external installations are needed. Python’s built-in shutil handles high-level file and folder operations, os interacts with the file system, pathlib provides cross-platform path handling, and datetime creates unique timestamped names for each backup.
import os
import shutil
from datetime import datetime
from pathlib import PathDefining source and destination
# Define pathsBackup function with timestamp
def run_backup():Convert to a standalone app
Once your backup script is working, you can convert it to a .exe so it runs on any Windows machine without Python installed, or schedule it with Windows Task Scheduler or cron on Linux to run daily automatically.
shutil functions reference
| Function | What it does |
|---|---|
| shutil.copytree(src, dst) | Copy entire folder tree |
| shutil.copy2(src, dst) | Copy single file preserving metadata |
| shutil.make_archive(name, ‘zip’, src) | Create a .zip of a folder |
| shutil.rmtree(path) | Delete folder and all contents |
Frequently asked questions
How do I back up only specific file types?
Use pathlib.glob() or os.walk() to iterate and filter by extension, then use shutil.copy2() for each matching file instead of copytree().
Can I back up to cloud storage?
Yes. If your cloud service mounts as a local drive (like OneDrive or Google Drive), use that path as dest_folder. For direct API uploads, use the respective SDK (Dropbox SDK, Google Drive API, etc.).
How do I schedule this to run daily?
On Windows, use Task Scheduler. On Linux/macOS, add a cron job: 0 2 * * * python3 /path/to/backup.py runs the script every day at 2 AM.






