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

王林
发布: 2024-08-16 18:01:09
原创
1044 人浏览过

Synchronizing Files Between Two Directories Using Python

在目录之间同步文件是管理备份、确保跨多个存储位置的一致性或简单地保持数据组织的常见任务。

虽然有许多工具可用于执行此操作,但创建 Python 脚本来处理目录同步可提供灵活性和控制力。

本指南将引导您完成一个旨在同步两个目录之间的文件的 Python 脚本。


脚本简介

该脚本首先导入几个基本的 Python 库。

其中包括用于与操作系统交互的 os、用于高级文件操作的 shutdownil、用于比较文件的 filecmp、用于解析命令行参数的 argparse 以及用于在长时间操作期间显示进度条的 tqdm。

这些库协同工作,为目录同步创建强大的解决方案。

import os
import shutil
import filecmp
import argparse
from tqdm import tqdm
登录后复制

脚本主要使用Python内置模块,但进度条使用tqdmlibrary,需要安装:

pip install tqdm
登录后复制

检查和准备目录

开始同步之前,脚本需要检查源目录是否存在。

如果目标目录不存在,脚本将创建它。

此步骤非常重要,可以确保同步过程顺利运行,不会出现因丢失目录而导致的任何问题。

# 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

登录后复制

check_directories 函数确保源目录和目标目录都已准备好同步。其工作原理如下:

  • 该函数使用 os.path.exists() 检查目录是否存在。
  • 如果源目录丢失,脚本会告诉用户并停止运行。
  • 如果目标目录丢失,脚本会使用 os.makedirs() 自动创建它。这可确保必要的目录结构就位。

在目录之间同步文件

该脚本的主要工作是同步源目录和目标目录之间的文件。

sync_directories 函数通过首先遍历源目录来收集所有文件和子目录的列表来处理此任务。

os.walk 函数通过在目录树中生成文件名来提供帮助,允许脚本捕获源目录中的每个文件和文件夹。

# 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)
登录后复制

编译文件和目录列表后,脚本将使用 tqdm 提供的进度条向用户提供有关同步过程的反馈。

对于源中的每个文件和目录,脚本计算目标中相应的路径。

如果路径是目录,脚本将确保它存在于目标中。

如果路径是文件,脚本会检查目标文件中是否已存在该文件以及它是否与源文件相同。

如果文件丢失或不同,脚本会将其复制到目标位置。

这样,脚本就可以使目标目录与源目录保持最新。


清理多余的文件

该脚本还有一个可选功能,可以删除目标目录中不在源目录中的文件。

这是由用户可以设置的 --delete 标志控制的。

如果使用此标志,脚本将遍历目标目录并将每个文件和文件夹与源进行比较。

如果在目标中发现源中没有的任何内容,脚本会将其删除。

这可确保目标目录是源目录的精确副本。

# 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)
登录后复制

这部分脚本使用与同步过程类似的技术。

它使用 os.walk() 来收集文件和目录,并使用 tqdm 来显示进度。
Shutil.rmtree() 函数用于删除目录,而 os.remove() 则处理单个文件。


运行脚本

该脚本设计为从命令行运行,参数指定源目录和目标目录。

argparse 模块可以轻松处理这些参数,允许用户在运行脚本时简单地提供必要的路径和选项。

# 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.")
登录后复制

主要功能将所有内容整合在一起。

它处理命令行参数,检查目录,然后执行同步。

如果设置了 --delete 标志,它还会处理额外文件的清理。


示例

让我们看一些如何使用不同选项运行脚本的示例。

出发地到目的地

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<00:00, 205.83file/s]
Copying d:\sync\video_single - Copy.mp4 to d:\sync2\video_single - Copy.mp4
Processing 'd:\sync\video_single.mp4':  80%|██████████████████████████████████████████████████████████████████▍                | 4/5 [00:00<00:00, 274.44file/s] 
Copying d:\sync\video_single.mp4 to d:\sync2\video_single.mp4
Processing 'd:\sync\video_single.mp4': 100%|███████████████████████████████████████████████████████████████████████████████████| 5/5 [00:00<00:00, 343.05file/s] 

Synchronization complete.
登录后复制

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<00:00, 63.29file/s]
Deleting files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 5/5 [00:00<?, ?file/s] 

Synchronization complete.
登录后复制

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.

以上是使用 Python 同步两个目录之间的文件的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!