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

运行效果

相关推荐
爱吃苹果的梨叔3 分钟前
2026年KVM over IP采购指南:BIOS级接管、并发和审计怎么验收
ide·python·tcp/ip·github
W优化大师5 分钟前
Windows 更新待处理弹窗一直不消失怎么解决,C 盘空间和后台任务该如何排查
windows·系统优化·磁盘清理·windows11·c盘·系统更新
Cloud_Shy6189 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第六章 Item 40 - 43)
android·开发语言·人工智能·笔记·python·学习方法
装不满的克莱因瓶9 分钟前
掌握生成对抗网络(GAN)的优化目标与评估指标——从博弈函数到生成质量衡量体系
人工智能·python·深度学习·算法·机器学习
半只小闲鱼15 分钟前
配置计划模块通用办公设备家具批复数合计计算
开发语言·python
是阿千呀!15 分钟前
A股市场风格切换研究:基于 Barra 风险模型的量化框架
python·量化
大蚂蚁2号27 分钟前
短视频批量生成技术深度解析与实战方案
python·aigc·音视频
努力写A题的小菜鸡36 分钟前
PyTorch 两种卷积写法彻底对比:F.conv2d 函数式 vs nn.Conv2d 类实战(超详细入门笔记)
python
golfscript37 分钟前
Playwright Python:微软出的浏览器自动化库
python·其他·microsoft·自动化
qq_4221525737 分钟前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word