Python - Windows下使用Python脚本同步一个文件夹下的所有文件到另一个文件夹下

Python同步文件

在Windows下使用Python脚本同步一个文件夹下的所有文件到另一个文件夹下

示例代码

python 复制代码
import logging
import os
import shutil


def sync_files(src_file_path, dst_dir_path, exclude_list):
    try:
        if not os.path.exists(src_file_path):
            os.makedirs(src_file_path)
        if not os.path.exists(dst_dir_path):
            os.makedirs(dst_dir_path)
        # 查找所有文件/文件夹
        for root, dirs, files in os.walk(src_folder_path):
            # 遍历添加创建所有文件夹
            for dir in dirs:
                if dir in exclude_list:
                    break
                dst_dir_path = os.path.join(dst_folder_path, os.path.relpath(os.path.join(root, dir), src_folder_path))
                if not os.path.exists(dst_dir_path):
                    os.makedirs(dst_dir_path)
            # 遍历添加文件
            for file in files:
                src_file_path = os.path.join(root, file)
                dst_file_path = os.path.join(dst_folder_path,
                                             os.path.relpath(os.path.join(root, file), src_folder_path))
                if file in exclude_list:
                    continue
                shutil.copy(src_file_path, dst_file_path)
        print("文件同步完成!")
    except Exception as e:
        logging.warning(f'文件同步出错 ===> error:{e}')


if __name__ == '__main__':
    src_folder_path = "D:/Johnson/myProject/project-gitee/easy-test-demo/test"
    dst_folder_path = "D:/Johnson/myProject/project-gitee/easy-test-demo/ttt"
    # 不同步的文件夹或文件列表
    exclude_list = ['.git-test', 'sync_local_code.bat', 'tt1.py']
    sync_files(src_folder_path, dst_folder_path, exclude_list)

附上一个.bat脚本文件,把相应的目录设置好后需要同步文件的时候双击该文件即可执行,不需要在启动.py文件

bash 复制代码
title=Sync Code
color 0F
rem @echo off
cd %~dp0
set cd=%~dp0
set PY_HOME=D:\Python\python385
set PATH=%PATH%;%PY_HOME%;%PY_HOME%/Scripts;%cd%/Scripts
@echo on
python sync_files.py

:: 窗口停留
cmd /k

运行效果

相关推荐
Littlehero_12140 分钟前
QT自定义控件之热换站系统(源码开源)
开发语言·qt
meilindehuzi_a41 分钟前
Python 基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
caimouse1 小时前
ReactOS 窗口系统分析(5):可见区域与窗口 DC — vis.c + windc.c
c语言·开发语言
Zane19941 小时前
调用了 async 函数却没执行?一文讲透协程、event loop 与 await
后端·python
OPEN-F1 小时前
Python进阶教程:装饰器与生成器深入
开发语言·python
zhipujiaoyu1 小时前
2026年大数据专科何去何从?就业前景、发展趋势全揭秘!
大数据·python
l1258651 小时前
# RAG噪声知识库治理:一致性与可信度的四层防线设计
数据库·人工智能·python·自然语言处理·langchain
zoujiahui_20181 小时前
别再只写 np.random.seed() 了:default_rng 与 np.random、random 到底差在哪?
python
Patrick在香港1 小时前
Claude Agent 进阶:4 种工具调用编排模式,让 0820 那 13 个 endpoint 并行起来
python·ai·ai编程
qq_513728042 小时前
StaleElementReferenceException(陈旧元素引用异常)
python