python(11) : 同步目录

 来自GTP

# -*- coding: utf-8 -*-

# ====> 同步代码 <==== #

import os
import shutil
import time
import traceback

ignore_dirs = ['.git']
ignore_files = ['cmd.cpython-310.pyc','','index.cpython-310.pyc','prompt_templates.cpython-310.pyc']

def copy_files(source_folder, destination_folder):
    for root, dirs, files in os.walk(source_folder):
        # 处理文件
        for file in files:
            source_file = os.path.join(root, file)
            relative_path = os.path.relpath(source_file, source_folder)
            destination_file = os.path.join(destination_folder, relative_path)
            if not os.path.exists(destination_file) or (
                    os.path.exists(destination_file) and os.stat(source_file).st_mtime > os.stat(
                destination_file).st_mtime):
                if source_file not in ignore_files :
                    shutil.copy(source_file, destination_file)
                    print(f"Copied 【file】 {source_file} to {destination_file}")

        # 处理子文件夹
        for subdir in dirs:
            source_subdir = os.path.join(root, subdir)
            relative_path = os.path.relpath(source_subdir, source_folder)
            destination_subdir = os.path.join(destination_folder, relative_path)
            if not os.path.exists(destination_subdir):
                if source_subdir not in ignore_dirs :
                    shutil.copytree(source_subdir, destination_subdir)
                    print(f"Copied 【dir】 {source_subdir} to {destination_subdir}")
            else:
                copy_files(source_subdir, destination_subdir)


def run(source_folder, destination_folder):
    print(f'start sync file, source:【{source_folder}】, target:【{destination_folder}】 ...')
    try:
        st = time.time()
        copy_files(source_folder, destination_folder)
        print(f'√√√ sync file completed, time consuming:[{round(time.time() - st, 2)}]second √√√')
    except Exception:
        print(f'××× sync file error ×××')
        traceback.print_exc()



if __name__ == '__main__':
    source_folder = "/your/source/folder/path"
    destination_folder = "/your/destination/folder/path"
    run(source_folder, destination_folder)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值