吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 974|回复: 24
收起左侧

[Python 原创] 文件夹和文件镜像备份的小程序

[复制链接]
psqladm 发表于 2025-12-5 22:47
作为一名办公室牛马,不管是由于系统崩溃、误删等等原因,辛苦劳作一段时间的文件再也找不到了,这种情况估计很多人都遇到过。
你永远不知道惊喜和意外,哪个先到,做好备份,有备无患。
这个小程序,逻辑简单,程序短小,没啥技术含量,如果能帮到需要的人,也会很开心。
使用说明:
1、编制一个文本文件,名为config.ini,和这个小程序放在同一目录下,格式如下:
[backup]
1.source = D:\document
1.destination = F:\document

2.source = D:\合同草稿.docx
2.destination = F:\合同草稿.docx

。。。。等等,序号按顺序增加

2、源文件存在,目标文件不存在的,会创建目录,拷贝文件;
源文件没有更改的,如果目标文件已存在,不会拷贝;
源文件做了修改或新增,会拷贝到目标文件;
源文件删除,如果目标文件存在,也会删除;

实现的是源文件和目标文件的镜像功能。

[Python] 纯文本查看 复制代码
#!/usr/bin/env python
# coding=utf-8

import configparser
import os
import shutil
import msvcrt

def copy_file_if_newer(src, dst):
    if not os.path.exists(dst):
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        shutil.copy2(src, dst)
        print(f"✅ Copied new file: {src} -> {dst}")
    else:
        if os.path.getmtime(src) > os.path.getmtime(dst):
            shutil.copy2(src, dst)
            print(f"🔄 Updated file: {src} -> {dst}")
        else:
            print(f"⏭️ Not newer: {src}")


def sync_folder(src_dir, dst_dir):
    # 确保目标目录存在
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
        print(f"📁 Created target dir: {dst_dir}")

    # 获取源和目标的内容集合(用于对比)
    src_items = set(os.listdir(src_dir)) if os.path.exists(src_dir) else set()
    dst_items = set(os.listdir(dst_dir)) if os.path.exists(dst_dir) else set()

    # 1. 同步源中存在的项目
    for item in src_items:
        s = os.path.join(src_dir, item)
        d = os.path.join(dst_dir, item)
        if os.path.isdir(s):
            sync_folder(s, d)
        else:
            copy_file_if_newer(s, d)

    # 2. 删除目标中存在但源中已删除的项目
    for item in (dst_items - src_items):
        d = os.path.join(dst_dir, item)
        if os.path.isdir(d):
            shutil.rmtree(d)
            print(f"🗑️ Deleted obsolete dir: {d}")
        else:
            os.remove(d)
            print(f"🗑️ Deleted obsolete file: {d}")


def main():
    config = configparser.ConfigParser(interpolation=None)
    config.read('config.ini', encoding='utf-8')

    if 'backup' not in config:
        print("❌ No [backup] section")
        return

    idx = 1
    while True:
        src_key = f"{idx}.source"
        dst_key = f"{idx}.destination"
        if src_key not in config['backup'] or dst_key not in config['backup']:
            break
        source = config['backup'][src_key].strip()
        destination = config['backup'][dst_key].strip()

        if not os.path.exists(source):
            # 源不存在:如果是文件,且目标存在,则删除目标
            if os.path.isfile(destination) and os.path.exists(destination):
                os.remove(destination)
                print(f"🗑️ Source file gone, deleted target: {destination}")
            elif os.path.isdir(destination) and os.path.exists(destination):
                shutil.rmtree(destination)
                print(f"🗑️ Source dir gone, deleted target: {destination}")
            else:
                print(f"⚠️ Source not found and no target to clean: {source}")
            idx += 1
            continue

        # 源存在:正常同步
        if os.path.isdir(source):
            print(f"\n📂 Dir: {source} => {destination}")
            sync_folder(source, destination)
        else:
            print(f"\n📄 File: {source} => {destination}")
            copy_file_if_newer(source, destination)

        idx += 1


if __name__ == "__main__":
    try:
        main()
    finally:
        print("\n" + "=" * 50)
        print("✅ 同步完成!请按任意键退出...")
        msvcrt.getch()

免费评分

参与人数 1吾爱币 +7 热心值 +1 收起 理由
hrh123 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| psqladm 发表于 2025-12-6 06:58
szmsys 发表于 2025-12-6 06:06
源文件删除,如果目标文件存在,也会删除。

这样的备份有啥用?

有一种备份方式,叫镜像备份,程序实现的是这种方式。
每个人的需求可能都不完全一样。
源程序已经提供了,您完全可以修改成您需要的备份方式。
 楼主| psqladm 发表于 2025-12-6 08:05
gwgdaemon 发表于 2025-12-5 23:27
做个开机启动,定时检测

我是编译成了exe文件,放在备份盘上,每天下班关机之前,运行一次。
Python文件拷贝速度比windows文件资源管理器快的多。
 楼主| psqladm 发表于 2025-12-6 09:30
风经过 发表于 2025-12-6 09:14
不错,忘性大的人,需要加入开机自启

设置“开机自启” + “每天 17:30 运行”
使用 任务计划程序 创建两个任务(或一个任务满足两个条件):

打开任务计划程序:
按 Win + R,输入 taskschd.msc,回车。
创建任务(推荐一个任务同时满足两个触发器)
右键“任务计划程序库” → 创建任务
常规选项卡:
名称:Sync Backup Daily
勾选:“不管用户是否登录都要运行”
勾选:“使用最高权限运行”
触发器选项卡 → 新建:
触发器1:启动时 → 确定
触发器2:每天 → 开始时间设为 17:30:00,重复间隔可选“每1天”
操作选项卡 → 新建:
操作:启动程序
程序/脚本:编译好的exe文件的完整路径
条件选项卡:
取消勾选“只有在计算机使用交流电源时才启动此任务”(如果你希望笔记本电池也运行)
确定,输入密码(如果要求)
gwgdaemon 发表于 2025-12-5 23:27
做个开机启动,定时检测
szmsys 发表于 2025-12-6 06:06
源文件删除,如果目标文件存在,也会删除。

这样的备份有啥用?
pojiestudy 发表于 2025-12-6 09:11
应该比较实用的小程序,谢谢分享
风经过 发表于 2025-12-6 09:14
不错,忘性大的人,需要加入开机自启
chshxp 发表于 2025-12-6 11:01
这正是我所需要的,谢谢!
风经过 发表于 2025-12-6 11:04
psqladm 发表于 2025-12-6 09:30
设置“开机自启” + “每天 17:30 运行”
使用 任务计划程序 创建两个任务(或一个任务满足两个条件): ...

很详细,感谢!!
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-12-12 11:42

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表