You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单向文件夹同步程序问题修复及完整实现请求

单向文件夹同步程序问题修复方案

问题1:日志文件仅记录单行内容

原因

每次写入日志时使用open("D:\log.txt", "w"),"w"模式会清空原有文件内容后写入新数据,循环中每次处理文件都会覆盖之前的日志,最终只保留最后一次操作的记录。

修复方式

  • 使用"a"模式打开日志文件,实现内容追加
  • 用with语句管理文件对象,自动完成文件关闭,避免资源泄漏
  • 日志中添加操作的具体时间(精确到时分秒),便于追溯

问题2:同步时间无法实时更新

原因

CurrentData在循环外部仅初始化一次,获取的是程序启动时的时间,循环内没有重新获取当前时间,导致输出始终是初始值。

修复方式

将当前时间的获取逻辑放入while循环内部,每次同步执行时重新获取最新时间。


修复并优化后的完整代码

import os
import shutil
from time import sleep
from datetime import datetime

print('Synchronization will be done every 60 seconds')

# 获取源文件夹路径
print('Please write Location of main Folder, Example:D:\FolderOne\\')
source_folder = input().strip()
# 确保路径结尾有分隔符,避免拼接错误
if not source_folder.endswith(os.sep):
    source_folder += os.sep

# 获取副本文件夹路径
print('Please write Location of replica Folder, Example:D:\FolderTwo\\')
destination_folder = input().strip()
if not destination_folder.endswith(os.sep):
    destination_folder += os.sep

# 确保副本文件夹存在
os.makedirs(destination_folder, exist_ok=True)

while True:
    # 每次同步时获取当前时间
    current_time = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
    
    # 同步源文件夹中的文件到副本
    for file_name in os.listdir(source_folder):
        source_path = os.path.join(source_folder, file_name)
        dest_path = os.path.join(destination_folder, file_name)
        
        if os.path.isfile(source_path):
            # 仅当文件有更新时才复制(对比修改时间)
            if not os.path.exists(dest_path) or os.path.getmtime(source_path) > os.path.getmtime(dest_path):
                shutil.copy2(source_path, dest_path)  # copy2保留文件元数据
                log_msg = f"[{current_time}] File '{file_name}' copied from '{source_folder}' to '{destination_folder}'"
                print(log_msg)
                # 追加写入日志
                with open("D:\log.txt", "a", encoding="utf-8") as f:
                    f.write(log_msg + "\n")
    
    # 删除副本中存在但源文件夹没有的文件
    for file_name in os.listdir(destination_folder):
        dest_path = os.path.join(destination_folder, file_name)
        source_path = os.path.join(source_folder, file_name)
        if os.path.isfile(dest_path) and not os.path.exists(source_path):
            os.remove(dest_path)
            log_msg = f"[{current_time}] File '{file_name}' deleted from '{destination_folder}' (not present in source)"
            print(log_msg)
            with open("D:\log.txt", "a", encoding="utf-8") as f:
                f.write(log_msg + "\n")
    
    print(f"Last time updated at: {current_time}")
    sleep(60)
    os.system('cls' if os.name == 'nt' else 'clear')

额外优化说明

  1. 使用os.path.join拼接路径,避免手动拼接时的分隔符问题,适配不同操作系统
  2. 用copy2替代copy,保留文件的修改时间、权限等元数据
  3. 增加文件更新判断,仅当源文件比副本新或副本不存在时才复制,减少不必要的操作
  4. 补充删除副本中多余文件的逻辑,确保副本与源文件夹完全一致
  5. 日志添加时间戳,提升可读性和追溯性
  6. 自动创建副本文件夹(如果不存在),避免路径不存在的错误

内容的提问来源于stack exchange,提问作者GeorGe Chanturia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:35:14