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

运行效果

相关推荐
happylifetree4 小时前
Python09:核心语法-数据存储与运算-字面量
python
落魄实习生4 小时前
Agent Scope Java 2.x 系列【7】工具使用
java·开发语言·ai
心之语歌4 小时前
Tkinter 画布基本梳理
运维·服务器·python
茉莉玫瑰花茶4 小时前
GO [ 方法 ]
开发语言·后端·golang
Wx-bishekaifayuan4 小时前
django个性化旅游路线推荐平台49005-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
狗凯之家源码网5 小时前
微博图床 PHP 系统搭建与实战应用指南
android·开发语言·php
万年咸鱼5 小时前
Qt Windows 使用管理员权限运行 Cmd
windows
小白快快跑哦5 小时前
python-字符串全解(六):正则表达式-量词
python·正则表达式·字符串
禹凕6 小时前
机器学习之Selenium(Machina Learning about Selenium)
爬虫·python·selenium·测试工具·机器学习
乌暮6 小时前
深入理解 Java 泛型:把「万能盒子」用对、用稳
java·开发语言·后端·学习