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

如何用Python基于文件名内嵌时间戳对文件分组统计与批量处理

Python实现按文件名内嵌日期归类统计文件

功能说明

  • 批量提取文件名内嵌的12位时间戳(格式为YYYYMMDDHHMM),截取前8位作为日期维度
  • 统计每日文件数量,支持两种排序输出:按日期升序、按文件数降序+日期升序
  • 预留同日期文件列表存储逻辑,方便后续扩展单日文件字数统计、内容分析等操作

输入示例

样例文件列表

  • Tyler Cowen On Reading 202109200657.md
  • On Poems 202109210659.md
  • Slava Akhmechet On Reading In Clusters 202109200659.md
  • Ideation In A 4X4 Matrix 202109200717.md
  • Drawing Grid Ideation 202109220830.md
  • Dictation 201208251425.md

输出要求

按日期升序的基础输出(用于Plotly绘图)

20120825,1
20210920,3
20210921,1
20210922,1

按文件数降序+日期升序的排序输出

20210920,3
20120825,1
20210921,1
20210922,1

实现代码

import os
import re
from collections import defaultdict

# 配置项:修改为你的md文件所在目录
FILE_DIR = "./your_files_path"
# 正则匹配文件名末尾的12位时间戳
DATE_PATTERN = re.compile(r"(\d{12})\.md$")

# 存储统计结果:key为8位日期,value为(文件数, 同日期文件路径列表)
date_stats = defaultdict(lambda: [0, []])

# 遍历目录统计
for filename in os.listdir(FILE_DIR):
    if not filename.endswith(".md"):
        continue
    match_res = DATE_PATTERN.search(filename)
    if not match_res:
        # 跳过不符合命名规则的文件
        continue
    full_timestamp = match_res.group(1)
    date_key = full_timestamp[:8]
    date_stats[date_key][0] += 1
    date_stats[date_key][1].append(os.path.join(FILE_DIR, filename))

# 1. 按日期升序输出(用于Plotly)
sorted_by_date = sorted(date_stats.items(), key=lambda x: x[0])
print("按日期升序输出:")
for date, (count, _) in sorted_by_date:
    print(f"{date},{count}")

# 2. 按文件数降序、日期升序输出
sorted_by_count = sorted(date_stats.items(), key=lambda x: (-x[1][0], x[0]))
print("\n按文件数降序输出:")
for date, (count, file_list) in sorted_by_count:
    print(f"{date},{count}")
    # 后续扩展:此处可加单日文件处理逻辑,比如统计总字数
    # total_word = 0
    # for file_path in file_list:
    #     with open(file_path, 'r', encoding='utf-8') as f:
    #         total_word += len(f.read().replace("\n", "").replace(" ", ""))
    # print(f"{date}总字数:{total_word}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:36:02