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

需求:基于文件创建日期时间复制文件的Python脚本(附代码)

按文件创建日期时间复制文件的Python脚本

需求说明

我需要一个Python脚本,能够根据文件的创建日期和时间将文件从一个文件夹复制到另一个文件夹。假设文件的创建日期为2023年2月22日、时间为上午6点,那么脚本需复制所有创建日期为2023年2月22日且时间为6点或6点之后的文件。

修正后的可用脚本

import os
import shutil
from datetime import datetime
from xml.dom import minidom

# 从XML配置文件读取源目录和目标目录
for file_node in minidom.parse('fileconfig.xml').getElementsByTagName('file'):
    source_path = file_node.getElementsByTagName("sourcepath")[0].firstChild.data.replace('"', '')
    dest_path = file_node.getElementsByTagName("mockpath")[0].firstChild.data.replace('"', '')

    # 定义需要筛选的目标日期时间(2023年2月22日6:00)
    target_datetime = datetime(2023, 2, 22, 6, 0, 0)

    # 遍历源目录下的所有文件
    for root, _, files in os.walk(source_path):
        for filename in files:
            file_full_path = os.path.join(root, filename)
            
            # 兼容不同系统获取文件创建时间
            try:
                # Windows系统用getctime获取创建时间
                file_creation_time = datetime.fromtimestamp(os.path.getctime(file_full_path))
            except AttributeError:
                # Unix/Linux/macOS系统用getbirthtime获取创建时间
                file_creation_time = datetime.fromtimestamp(os.path.getbirthtime(file_full_path))
            
            # 判断文件是否符合时间条件
            if file_creation_time >= target_datetime:
                print(f"复制文件: {file_full_path}")
                # 复制文件并保留元数据(创建时间、权限等)
                shutil.copy2(file_full_path, dest_path)
                print(f"已复制至: {os.path.join(dest_path, filename)}")

关键细节说明

  • 跨系统兼容性:不同系统获取文件创建时间的API不同,脚本做了兼容处理,避免因系统差异报错。
  • 精准时间判断:直接用datetime对象做比较,比字符串拼接后判断更可靠,不会出现格式不匹配的问题。
  • 配置文件处理:自动去除路径字符串中的多余引号,避免路径解析失败。
  • 完整复制:使用shutil.copy2复制文件,能保留原文件的元数据(如创建时间、权限),比普通复制更实用。

原代码的问题修正点

  • 时间类型错误:原代码误用os.path.getmtime(文件修改时间)代替创建时间,导致判断依据错误。
  • 变量冲突:原代码把time模块覆盖成了字符串变量,导致后续无法调用time模块的方法。
  • 逻辑反转:原代码判断条件写反,会复制目标时间之前的文件,和需求完全相反。
  • 缩进混乱:Python对缩进敏感,原代码多处缩进错误,导致逻辑执行异常。
  • 语法错误:else语句缩进错误且使用了不必要的大括号,不符合Python语法规范。

内容的提问来源于stack exchange,提问作者Tejas palwe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:37:35