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

文件批量重命名后排序异常,求技术指导

问题描述

我正在编写一个程序,用于为文件夹内所有.txt文件重命名并添加前缀,但程序添加前缀重命名后,文件顺序变得混乱,我需要按文件名中的日期时间对文件进行排序。

以下是我的代码:

from datetime import datetime
from pathlib import Path

files = Path("D:/")
count = 1
for file in files.iterdir():
    if file.is_file() and file.suffix == '.txt':
        directory = file.parent
        extension = file.suffix

        old_name = file.stem
        old_name, old_date, old_time = old_name.split(' ')

        old_date = datetime.strptime(old_date, '%d%m%y')
        date = datetime.strftime(old_date, '%d.%m.%y')

        new_prefix = '(AY5.{}) '.format(count)
        new_name = f'{new_prefix} {date} {old_time}{extension}'


        new_path = files.joinpath('Renamed files')

        if not new_path.exists():
            new_path.mkdir()

        new_file_path = new_path.joinpath(new_name)

        file.replace(new_file_path)
        count += 1


new_files_dir = Path("D:/Renamed files")
with open('file names.txt', 'w+') as f:
    for new_files in new_files_dir.iterdir():
        if new_files.is_file() and new_files.suffix == '.txt':
            f.write(new_files.stem + '\n')

f.close()
解决方案

问题核心是iterdir()返回的文件顺序由操作系统文件系统决定,没有固定规则,导致重命名后的前缀序号与时间顺序不匹配。要解决这个问题,需要先提取每个文件的日期时间信息,按时间排序后再执行重命名和后续操作。

修改步骤

  • 收集所有目标txt文件,解析文件名中的日期时间字符串生成可排序的datetime对象
  • 以日期时间为依据对文件列表排序
  • 遍历排序后的列表完成重命名
  • 写入文件名时同样按时间排序,保证输出顺序正确

修改后的代码

from datetime import datetime
from pathlib import Path

files_dir = Path("D:/")
txt_files = []

# 收集文件并提取时间信息
for file in files_dir.iterdir():
    if file.is_file() and file.suffix == '.txt':
        try:
            # 拆分原文件名,假设格式为"名称 日期 时间"
            _, old_date_str, old_time = file.stem.split(' ')
            # 合并日期时间字符串为datetime对象,时间格式请根据实际情况调整(示例为HHMMSS)
            file_datetime = datetime.strptime(f"{old_date_str} {old_time}", '%d%m%y %H%M%S')
            txt_files.append((file_datetime, file))
        except ValueError:
            # 处理格式不符合预期的文件,可根据需求调整逻辑
            print(f"跳过格式异常文件:{file.name}")

# 按日期时间从小到大排序
txt_files.sort(key=lambda x: x[0])

# 创建目标目录,exist_ok=True避免重复创建报错
new_path = files_dir.joinpath('Renamed files')
new_path.mkdir(exist_ok=True)

# 执行重命名
count = 1
for file_datetime, file in txt_files:
    extension = file.suffix
    _, old_date_str, old_time = file.stem.split(' ')
    
    old_date = datetime.strptime(old_date_str, '%d%m%y')
    date_str = datetime.strftime(old_date, '%d.%m.%y')
    
    new_prefix = '(AY5.{}) '.format(count)
    new_name = f'{new_prefix} {date_str} {old_time}{extension}'
    new_file_path = new_path.joinpath(new_name)
    
    file.replace(new_file_path)
    count += 1

# 按时间顺序写入文件名到文件
with open('file names.txt', 'w') as f:
    renamed_files = []
    for file in new_path.iterdir():
        if file.is_file() and file.suffix == '.txt':
            # 从新文件名提取日期时间用于排序
            _, date_part, time_part = file.stem.split(' ', 2)
            # 转换回原日期格式解析
            file_datetime = datetime.strptime(f"{date_part.replace('.', '')} {time_part}", '%d%m%y %H%M%S')
            renamed_files.append((file_datetime, file))
    
    renamed_files.sort(key=lambda x: x[0])
    for _, file in renamed_files:
        f.write(file.stem + '\n')

关键说明

  • 通过datetime对象实现精准的时间排序,避免字符串排序带来的误差(比如"01.01.24"和"12.12.23"的字符串排序结果不符合时间逻辑)
  • 新增异常处理,防止因个别文件名格式错误导致程序中断
  • 使用mkdir(exist_ok=True)简化目录创建逻辑,无需额外判断目录是否存在
  • 写入文件名时再次排序,确保输出的file names.txt内容按时间顺序排列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:57:22