Backing up files to an external drive using Python

Several months ago, I wanted to start regularly backing up the important files on my laptop. I set up cloud-based syncing of my files, including version history, but I felt like I needed to have a redundant physical backup that I occasionally would update. I had an external drive, so I looked into some programs that would automatically copy or update my files. None of them seemed to work well, they took a long time to run, I couldn’t easily view the backup files, or they kept pushing me to upgrade to a premium service for more features. So, instead I wrote my own (link to the code).

# File:

import dirsync
import os

src = "Path_To_Folder_Being_Backedup"
dest = "Path_To_External_Drive"

if os.path.exists(dest):
    dirsync.sync(src, dest, 'sync', purge=True)
    print("Backup storage not found. Exiting...")

The code is simple. It uses the sync function from the dirsync package to sync files from the src folder on your computer to the dest folder on your external drive. The third argument 'sync' in the function ensures that all the files in src are updated or copied over if they are not already in dest. The purge option deletes files in dest that have been deleted in src. So, after the script is run, dest should be an exact copy of src.

To easily run the script, I created a batch script since I am on Windows, and saved it to my desktop for easy access anytime I plug in my external drive (for how to run Python scripts, check out Automate the Boring Stuff with Python Appendix B).

@py "C:\Users\path_to_file\" %*

The initial copy of the files took a long time, but after that it only updates the ones that have been added, deleted, or modified, so it usually runs pretty quickly!