作为一名办公室牛马,不管是由于系统崩溃、误删等等原因,辛苦劳作一段时间的文件再也找不到了,这种情况估计很多人都遇到过。
你永远不知道惊喜和意外,哪个先到,做好备份,有备无患。
这个小程序,逻辑简单,程序短小,没啥技术含量,如果能帮到需要的人,也会很开心。
使用说明:
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()
|