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

如何用Python按文件名的日期时间对文件夹内JSON文件排序?

解决按文件名时间排序遍历JSON文件的问题

你的代码有两个关键问题:

  1. json_files = []被放在循环内部,每次循环都会清空列表,最后只能保留最后一个文件的数据
  2. 依赖文件修改时间排序不可靠,而你的文件名本身就包含了精确的时间戳,直接用这个来排序才是最准确的

修正后的代码

import os
import json
from datetime import datetime

dir_path = 'data/41'
json_files = []

# 第一步:收集所有JSON文件路径及对应时间
for file_name in os.listdir(dir_path):
    if file_name.endswith('.json'):
        file_path = os.path.join(dir_path, file_name)
        # 从文件名提取时间字符串(去掉末尾的.json后缀)
        time_str = file_name[:-5]
        try:
            # 解析时间字符串为可排序的datetime对象
            file_datetime = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S.%f')
            json_files.append({
                'path': file_path,
                'datetime': file_datetime
            })
        except ValueError:
            # 跳过格式不符合的文件
            continue

# 第二步:按文件名中的时间戳排序
json_files.sort(key=lambda x: x['datetime'])

# 第三步:读取排序后的JSON数据并整理
result_dict = {}  # 可根据需求调整为列表或其他结构
for item in json_files:
    try:
        with open(item['path'], 'r') as f:
            json_data = json.load(f)
            # 示例:按时间戳作为键存入字典,也可直接追加到列表
            result_dict[item['datetime'].isoformat()] = json_data
    except json.JSONDecodeError:
        print(f"跳过无效JSON文件:{item['path']}")
    except Exception as e:
        print(f"读取文件出错:{item['path']},错误:{e}")

关键说明

  • 完全基于文件名自带的时间戳排序,彻底摆脱对文件修改时间的依赖,准确性拉满
  • 先收集所有文件的时间信息并排序,再读取数据,保证遍历顺序严格按时间排列
  • 增加了对非JSON文件、格式错误文件的过滤逻辑,避免程序意外崩溃
  • 可根据实际需求调整result_dict的存储逻辑(比如用列表存储所有JSON数据,或者合并相同键的内容)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:50:23