Categories We Write About

Build a script to auto-sync folders

Here’s a simple Python script that can auto-sync two folders by copying new or changed files from a source folder to a destination folder. It uses the filecmp and shutil modules to compare and copy files, and can be run periodically or as a continuous sync if you want.

python
import os import filecmp import shutil import time def sync_folders(source, destination): # Ensure destination folder exists if not os.path.exists(destination): os.makedirs(destination) # Compare directory contents comparison = filecmp.dircmp(source, destination) # Copy files from source to destination if missing or different for file_name in comparison.left_only + comparison.diff_files: src_file = os.path.join(source, file_name) dst_file = os.path.join(destination, file_name) if os.path.isdir(src_file): shutil.copytree(src_file, dst_file, dirs_exist_ok=True) print(f"Copied folder: {src_file} to {dst_file}") else: shutil.copy2(src_file, dst_file) print(f"Copied file: {src_file} to {dst_file}") # Recursively sync common subdirectories for common_dir in comparison.common_dirs: sync_folders(os.path.join(source, common_dir), os.path.join(destination, common_dir)) # Optionally: Remove files/folders in destination not in source for file_name in comparison.right_only: dst_path = os.path.join(destination, file_name) if os.path.isdir(dst_path): shutil.rmtree(dst_path) print(f"Removed folder: {dst_path}") else: os.remove(dst_path) print(f"Removed file: {dst_path}") if __name__ == "__main__": source_folder = "/path/to/source" destination_folder = "/path/to/destination" # Run one time sync sync_folders(source_folder, destination_folder) # Or run continuous sync every 10 seconds (uncomment below) # while True: # sync_folders(source_folder, destination_folder) # time.sleep(10)

How it works:

  • Compares source and destination folders.

  • Copies new or updated files/folders from source to destination.

  • Removes files/folders from destination that are no longer in source.

  • Supports recursive syncing of subdirectories.

Change the source_folder and destination_folder variables to your paths and run the script. You can uncomment the loop for continuous syncing with a delay.

Let me know if you want it adapted to other languages or with extra features!

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About