”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Python 同步两个目录之间的文件

使用 Python 同步两个目录之间的文件

发布于2024-08-16
浏览:927

Synchronizing Files Between Two Directories Using Python

Synchronizing files between directories is a common task for managing backups, ensuring consistency across multiple storage locations, or simply keeping data organized.

While there are many tools available to do this, creating a Python script to handle directory synchronization offers flexibility and control.

This guide will walk you through a Python script designed to synchronize files between two directories.


Introduction to the Script

The script begins by importing several essential Python libraries.

These include os for interacting with the operating system, shutilfor high-level file operations, filecmpfor comparing files, argparsefor parsing command-line arguments, and tqdmfor displaying progress bars during lengthy operations.

These libraries work together to create a robust solution for directory synchronization.

import os
import shutil
import filecmp
import argparse
from tqdm import tqdm

The scripts uses mainly Python built-in modules, but for the progress bar is uses the tqdmlibrary, which needs to the installed with:

pip install tqdm

Checking and Preparing Directories

Before starting the synchronization, the script needs to check if the source directory exists.

If the destination directory doesn't exist, the script will create it.

This step is important to make sure the synchronization process can run smoothly without any issues caused by missing directories.

# Function to check if the source and destination directories exist
def check_directories(src_dir, dst_dir):
    # Check if the source directory exists
    if not os.path.exists(src_dir):
        print(f"\nSource directory '{src_dir}' does not exist.")
        return False
    # Create the destination directory if it does not exist
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
        print(f"\nDestination directory '{dst_dir}' created.")
    return True

The check_directories function makes sure that both the source and destination directories are ready for synchronization. Here's how it works:

  • The function uses os.path.exists() to check if the directories exist.
  • If the source directory is missing, the script tells the user and stops running.
  • If the destination directory is missing, the script creates it automatically using os.makedirs(). This ensures that the necessary directory structure is in place.

Synchronizing Files Between Directories

The main job of the script is to synchronize files between the source and destination directories.

The sync_directories function handles this task by first going through the source directory to gather a list of all files and subdirectories.

The os.walk function helps by generating file names in the directory tree, allowing the script to capture every file and folder within the source directory.

# Function to synchronize files between two directories
def sync_directories(src_dir, dst_dir, delete=False):
    # Get a list of all files and directories in the source directory
    files_to_sync = []
    for root, dirs, files in os.walk(src_dir):
        for directory in dirs:
            files_to_sync.append(os.path.join(root, directory))
        for file in files:
            files_to_sync.append(os.path.join(root, file))

    # Iterate over each file in the source directory with a progress bar
    with tqdm(total=len(files_to_sync), desc="Syncing files", unit="file") as pbar:
        # Iterate over each file in the source directory
        for source_path in files_to_sync:
            # Get the corresponding path in the replica directory
            replica_path = os.path.join(dst_dir, os.path.relpath(source_path, src_dir))

            # Check if path is a directory and create it in the replica directory if it does not exist
            if os.path.isdir(source_path):
                if not os.path.exists(replica_path):
                    os.makedirs(replica_path)
            # Copy all files from the source directory to the replica directory
            else:
                # Check if the file exists in the replica directory and if it is different from the source file
                if not os.path.exists(replica_path) or not filecmp.cmp(source_path, replica_path, shallow=False):
                    # Set the description of the progress bar and print the file being copied
                    pbar.set_description(f"Processing '{source_path}'")
                    print(f"\nCopying {source_path} to {replica_path}")

                    # Copy the file from the source directory to the replica directory
                    shutil.copy2(source_path, replica_path)

            # Update the progress bar
            pbar.update(1)

Once the list of files and directories is compiled, the script uses a progress bar provided by tqdm to give the user feedback on the synchronization process.

For each file and directory in the source, the script calculates the corresponding path in the destination.

If the path is a directory, the script ensures it exists in the destination.

If the path is a file, the script checks whether the file already exists in the destination and whether it is identical to the source file.

If the file is missing or different, the script copies it to the destination.

This way, the script keeps the destination directory up-to-date with the source directory.


Cleaning Up Extra Files

The script also has an optional feature to delete files in the destination directory that are not in the source directory.

This is controlled by a --delete flag that the user can set.

If this flag is used, the script goes through the destination directory and compares each file and folder to the source.

If it finds anything in the destination that isn't in the source, the script deletes it.

This ensures that the destination directory is an exact copy of the source directory.

# Clean up files in the destination directory that are not in the source directory, if delete flag is set
    if delete:
        # Get a list of all files in the destination directory
        files_to_delete = []
        for root, dirs, files in os.walk(dst_dir):
            for directory in dirs:
                files_to_delete.append(os.path.join(root, directory))
            for file in files:
                files_to_delete.append(os.path.join(root, file))

        # Iterate over each file in the destination directory with a progress bar
        with tqdm(total=len(files_to_delete), desc="Deleting files", unit="file") as pbar:
            # Iterate over each file in the destination directory
            for replica_path in files_to_delete:
                # Check if the file exists in the source directory
                source_path = os.path.join(src_dir, os.path.relpath(replica_path, dst_dir))
                if not os.path.exists(source_path):
                    # Set the description of the progress bar
                    pbar.set_description(f"Processing '{replica_path}'")
                    print(f"\nDeleting {replica_path}")

                    # Check if the path is a directory and remove it
                    if os.path.isdir(replica_path):
                        shutil.rmtree(replica_path)
                    else:
                        # Remove the file from the destination directory
                        os.remove(replica_path)

                # Update the progress bar
                pbar.update(1)

This part of the script uses similar techniques as the synchronization process.

It uses os.walk() to gather files and directories and tqdm to show progress.
The shutil.rmtree() function is used to remove directories, while os.remove() handles individual files.


Running the Script

The script is designed to be run from the command line, with arguments specifying the source and destination directories.

The argparse module makes it easy to handle these arguments, allowing users to simply provide the necessary paths and options when running the script.

# Main function to parse command line arguments and synchronize directories
if __name__ == "__main__":
    # Parse command line arguments
    parser = argparse.ArgumentParser(description="Synchronize files between two directories.")
    parser.add_argument("source_directory", help="The source directory to synchronize from.")
    parser.add_argument("destination_directory", help="The destination directory to synchronize to.")
    parser.add_argument("-d", "--delete", action="store_true",
                        help="Delete files in destination that are not in source.")
    args = parser.parse_args()

    # If the delete flag is set, print a warning message
    if args.delete:
        print("\nExtraneous files in the destination will be deleted.")

    # Check the source and destination directories
    if not check_directories(args.source_directory, args.destination_directory):
        exit(1)

    # Synchronize the directories
    sync_directories(args.source_directory, args.destination_directory, args.delete)
    print("\nSynchronization complete.")

The main function brings everything together.

It processes the command-line arguments, checks the directories, and then performs the synchronization.

If the --delete flag is set, it also handles the cleanup of extra files.


Examples

Let's see some examples of how to run the script with the different options.

Source to Destination

python file_sync.py d:\sync d:\sync_copy 
Destination directory 'd:\sync2' created.
Processing 'd:\sync\video.mp4':   0%|                                                                                                   | 0/5 [00:00, ?file/s]
Copying d:\sync\video.mp4 to d:\sync2\video.mp4
Processing 'd:\sync\video_final.mp4':  20%|██████████████████▌                                                                          | 1/5 [00:00, ?file/s] 
Copying d:\sync\video_final.mp4 to d:\sync2\video_final.mp4
Processing 'd:\sync\video_single - Copy (2).mp4':  40%|████████████████████████████████▍                                                | 2/5 [00:00, ?file/s] 
Copying d:\sync\video_single - Copy (2).mp4 to d:\sync2\video_single - Copy (2).mp4
Processing 'd:\sync\video_single - Copy.mp4':  60%|█████████████████████████████████████████████▌                              | 3/5 [00:00



Source to Destination with Cleanup of Extra Files

python file_sync.py d:\sync d:\sync_copy -d
Extraneous files in the destination will be deleted.
Syncing files: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████| 5/5 [00:00





Conclusion

This Python script offers a powerful and flexible way to synchronize files between two directories.

It uses key libraries like os, shutil, and filecmp, and enhances the user experience with tqdm for tracking progress.

This ensures that your data is consistently and efficiently synchronized.
Whether you're maintaining backups or ensuring consistency across storage locations, this script can be a valuable tool in your toolkit.

版本声明 本文转载于:https://dev.to/devasservice/synchronizing-files-between-two-directories-using-python-19li?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何使用 JSTL 迭代 HashMap 中的 ArrayList?
    如何使用 JSTL 迭代 HashMap 中的 ArrayList?
    使用 JSTL 迭代 HashMap 中的 ArrayList在 Web 开发中,JSTL(JavaServer Pages 标准标记库)提供了一组标记来简化 JSP 中的常见任务( Java 服务器页面)。其中一项任务是迭代数据结构。要迭代 HashMap 及其中包含的 ArrayList,可以使...
    编程 发布于2024-11-05
  • Encore.ts — 比 ElysiaJS 和 Hono 更快
    Encore.ts — 比 ElysiaJS 和 Hono 更快
    几个月前,我们发布了 Encore.ts — TypeScript 的开源后端框架。 由于已经有很多框架,我们想分享我们做出的一些不常见的设计决策以及它们如何带来卓越的性能数据。 性能基准 我们之前发布的基准测试显示 Encore.ts 比 Express 快 9 倍,比 Fasti...
    编程 发布于2024-11-05
  • 为什么使用 + 对字符串文字进行字符串连接失败?
    为什么使用 + 对字符串文字进行字符串连接失败?
    连接字符串文字与字符串在 C 中,运算符可用于连接字符串和字符串文字。但是,此功能存在限制,可能会导致混乱。在问题中,作者尝试连接字符串文字“Hello”、“,world”和“!”以两种不同的方式。第一个例子:const string hello = "Hello"; const...
    编程 发布于2024-11-05
  • React 重新渲染:最佳性能的最佳实践
    React 重新渲染:最佳性能的最佳实践
    React高效的渲染机制是其受欢迎的关键原因之一。然而,随着应用程序复杂性的增加,管理组件重新渲染对于优化性能变得至关重要。让我们探索优化 React 渲染行为并避免不必要的重新渲染的最佳实践。 1. 使用 React.memo() 作为函数式组件 React.memo() 是一个高...
    编程 发布于2024-11-05
  • 如何实现条件列创建:探索 Pandas DataFrame 中的 If-Elif-Else?
    如何实现条件列创建:探索 Pandas DataFrame 中的 If-Elif-Else?
    Creating a Conditional Column: If-Elif-Else in Pandas给定的问题要求将新列添加到 DataFrame 中基于一系列条件标准。挑战在于在实现这些条件的同时保持代码效率和可读性。使用函数应用程序的解决方案一种方法涉及创建一个将每一行映射到所需结果的函数...
    编程 发布于2024-11-05
  • 介绍邱!
    介绍邱!
    我很高兴地宣布发布 Qiu – 一个严肃的 SQL 查询运行器,旨在让原始 SQL 再次变得有趣。老实说,ORM 有其用武之地,但当您只想编写简单的 SQL 时,它们可能会有点让人不知所措。我一直很喜欢编写原始 SQL 查询,但我意识到我需要练习——大量的练习。这就是Qiu发挥作用的地方。 有了 Q...
    编程 发布于2024-11-05
  • 为什么 CSS 中的 Margin-Top 百分比是根据容器宽度计算的?
    为什么 CSS 中的 Margin-Top 百分比是根据容器宽度计算的?
    CSS 中的 margin-top 百分比计算当对元素应用 margin-top 百分比时,必须了解计算方式执行。与普遍的看法相反,边距顶部百分比是根据包含块的宽度而不是其高度来确定的。W3C 规范解释:根据W3C 规范,“百分比是根据生成的框包含块的宽度计算的。”此规则适用于“margin-top...
    编程 发布于2024-11-05
  • 如何解决 CSS 转换期间 Webkit 文本渲染不一致的问题?
    如何解决 CSS 转换期间 Webkit 文本渲染不一致的问题?
    解决 CSS 转换期间的 Webkit 文本渲染不一致在 CSS 转换期间,特别是缩放元素时,Webkit 中可能会出现文本渲染不一致的情况浏览器。这个问题源于浏览器尝试优化渲染性能。一种解决方案是通过添加以下属性来强制对过渡元素的父元素进行硬件加速:-webkit-transform: trans...
    编程 发布于2024-11-05
  • 使用 Reactables 简化 RxJS
    使用 Reactables 简化 RxJS
    介绍 RxJS 是一个功能强大的库,但众所周知,它的学习曲线很陡峭。 该库庞大的 API 界面,再加上向反应式编程的范式转变,可能会让新手不知所措。 我创建了 Reactables API 来简化 RxJS 的使用并简化开发人员对反应式编程的介绍。 例子 我们将构建...
    编程 发布于2024-11-05
  • 如何在 Pandas 中查找多列的最大值?
    如何在 Pandas 中查找多列的最大值?
    查找 Pandas 中多列的最大值要确定 pandas DataFrame 中多列的最大值,可以采用多种方法。以下是实现此目的的方法:对指定列使用 max() 函数此方法涉及显式选择所需的列并应用 max() 函数: df[["A", "B"]] df[[&q...
    编程 发布于2024-11-05
  • CI/CD 入门:自动化第一个管道的初学者指南(使用 Jenkins)
    CI/CD 入门:自动化第一个管道的初学者指南(使用 Jenkins)
    目录 介绍 什么是 CI/CD? 持续集成(CI) 持续交付(CD) 持续部署 CI/CD 的好处 更快的上市时间 提高代码质量 高效协作 提高自动化程度和一致性 如何创建您的第一个 CI/CD 管道 第 1 步:设置版本控制 (GitHub) 第 2 步:选择 CI/CD 工具 ...
    编程 发布于2024-11-05
  • TypeScript 如何使 JavaScript 在大型项目中更加可靠。
    TypeScript 如何使 JavaScript 在大型项目中更加可靠。
    介绍 JavaScript 广泛应用于 Web 开发,现在也被应用于不同行业的大型项目中。然而,随着这些项目的增长,管理 JavaScript 代码变得更加困难。数据类型不匹配、运行时意外错误以及代码不清晰等问题可能会导致查找和修复错误变得困难。 这就是TypeScript介入的地...
    编程 发布于2024-11-05
  • 如何使用PHP的password_verify函数安全地验证用户密码?
    如何使用PHP的password_verify函数安全地验证用户密码?
    使用 PHP 解密加密密码许多应用程序使用密码哈希等加密算法安全地存储用户密码。然而,在验证登录尝试时,将输入密码与加密的存储版本进行比较非常重要。加密问题password_hash 使用 Bcrypt,一种一元加密算法方式哈希算法,意味着加密的密码无法逆转或解密。这是一项安全功能,可确保即使数据库...
    编程 发布于2024-11-05
  • 学习 Vue 部分 构建天气应用程序
    学习 Vue 部分 构建天气应用程序
    深入研究 Vue.js 就像在 DIY 工具包中发现了一个新的最喜欢的工具——直观、灵活,而且功能强大得惊人。我接触 Vue 的第一个副业项目是一个天气应用程序,它教会了我很多关于框架功能以及一般 Web 开发的知识。这是我到目前为止所学到的。 1. Vue 入门:简单与强大 Vue...
    编程 发布于2024-11-05
  • NFT 预览卡组件
    NFT 预览卡组件
    ?刚刚完成了我的最新项目:使用 HTML 和 CSS 的“NFT 预览卡组件”! ?查看并探索 GitHub 上的代码。欢迎反馈! ? GitHub:[https://github.com/khanimran17/NFT-preview-card-component] ?现场演示:[https://...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3