w3resource

Python File Synchronization Tool

Write a Python program to develop a command-line tool that synchronizes files between two directories.

The task is to create a Python program that acts as a command-line tool for synchronizing files between two directories. This tool ensures that all files from the source directory are copied to the destination directory, maintaining the directory structure. The program will verify the existence of both directories, traverse the source directory, and replicate its files and subdirectories in the destination directory. This will keep the two directories in sync.

Sample Solution:

Python Code :

import os  # Import the os module for interacting with the operating system
import shutil  # Import the shutil module for file operations
import argparse  # Import the argparse module for command-line argument parsing

def synchronize(source_dir, destination_dir):
    # Ensure both directories exist
    if not os.path.exists(source_dir):
        print(f"Source directory '{source_dir}' does not exist.")
        return
    if not os.path.exists(destination_dir):
        print(f"Destination directory '{destination_dir}' does not exist.")
        return

    # Iterate over files in source directory
    for root, dirs, files in os.walk(source_dir):
        # Get corresponding path in destination directory
        relative_path = os.path.relpath(root, source_dir)
        dest_path = os.path.join(destination_dir, relative_path)

        # Ensure corresponding directory structure exists in destination
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)

        # Copy files from source to destination
        for file in files:
            source_file = os.path.join(root, file)
            dest_file = os.path.join(dest_path, file)
            shutil.copy2(source_file, dest_file)
            print(f"Copied: {source_file} -> {dest_file}")

    print("Synchronization complete.")

if __name__ == "__main__":
    # Create argument parser
    parser = argparse.ArgumentParser(description="Synchronize files between two directories.")
    # Add argument for source directory
    parser.add_argument("source", help="Source directory")
    # Add argument for destination directory
    parser.add_argument("destination", help="Destination directory")
    # Parse the command-line arguments
    args = parser.parse_args()

    # Call the synchronize function with the provided arguments
    synchronize(args.source, args.destination)

Output:

(base) C:\Users\ME> python untitled0.py f:\dir1 f:\dir2
Copied: f:\dir1\text1.txt -> f:\dir2\.\text1.txt
Copied: f:\dir1\text2.txt -> f:\dir2\.\text2.txt
Copied: f:\dir1\text3.txt -> f:\dir2\.\text3.txt
Synchronization complete.

Explanation:

  • Importing modules:
    os: Provides functions for interacting with the operating system.
  • shutil: Offers a higher-level interface for file operations.
  • argparse: Facilitates easy parsing of command-line arguments.
  • Function synchronize(source_dir, destination_dir):
  • Purpose: Synchronizes files from the source directory to the destination directory.
  • Directory Existence Check:
    Checks if the 'source_dir' exists. If not, it prints an error message and exits the function.
  • Checks if the 'destination_dir' exists. If not, it prints an error message and exits the function.
  • File iteration:
    Uses os.walk to traverse the 'source_dir' directory tree.
  • For each directory and its files:
    Relative Path Calculation: Computes the relative path of the current directory with respect to the 'source_dir'.
  • Destination Path Construction: Constructs the corresponding path in the 'destination_dir'.
  • Directory Structure Creation: Ensures the directory structure exists in the 'destination_dir'. If not, it creates the necessary directories.
  • File Copying: Copies each file from the 'source_dir' to the 'destination_dir' using 'shutil.copy2', which preserves metadata. Prints a message indicating each copied file.
  • Completion Message: Prints a message indicating the synchronization is complete.
  • Main Block:
  • Argument parsing:
    Creates an "ArgumentParser" object to handle command-line arguments.
  • Adds arguments for the source directory ('source') and the destination directory ('destination').
  • Parses the provided arguments and stores them in the 'args' object.
  • Function Call: Calls the 'synchronize' function with the parsed 'source' and 'destination' arguments.
  • Usage:
    Run the script from the command line with two arguments: the path to the source directory and the path to the destination directory.
  • Example command: python script_name.py /path/to/source /path/to/destination.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Python A* Search Algorithm for Pathfinding.
Next: Python Custom JSON Encoder and Decoder

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.