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

运行效果

相关推荐
Aision_1 小时前
从工具调用到 MCP、Skill完整学习记录
java·python·gpt·学习·langchain·prompt·agi
辞旧 lekkk5 小时前
【Qt】信号和槽
linux·开发语言·数据库·qt·学习·mysql·萌新
2zcode6 小时前
运动模糊图像复原的MATLAB仿真与优化
开发语言·matlab
袁雅倩19976 小时前
当吸尘器、筋膜枪都用上Type-C,供电方案该怎么选?浅谈PD取电芯片ECP5702的应用
c语言·开发语言·支持向量机·动态规划·推荐算法·最小二乘法·图搜索算法
2301_809204706 小时前
JavaScript中严格模式use-strict对引擎解析的辅助.txt
jvm·数据库·python
zjy277777 小时前
mysql如何选择合适的索引类型_mysql索引设计实战
jvm·数据库·python
Aaswk7 小时前
Java Lambda 表达式与流处理
java·开发语言·python
万邦科技Lafite7 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
Cyber4K8 小时前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php
Le_ee8 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php