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

如何查找指定后缀文件、提取文件名时间并按序存储到数组?

没问题,我来帮你搞定这个按时间排序文件的需求!下面是具体的实现思路和代码示例(以Python为例,毕竟处理文件排序这类场景它非常顺手):

解决方案:按文件名中的时间信息排序并读取目标文件

我们需要分三步完成核心操作:筛选出目标文件、提取时间并转换为可排序的依据、按时间排序后处理文件,具体如下:

1. 先筛选出所有以triang.dat结尾的文件

用glob模块可以快速匹配符合规则的文件,省去手动遍历判断的麻烦:

import glob

# 替换成你的文件夹实际路径
target_folder = "/your/folder/path/here"
# 匹配所有xxx_triang.dat格式的文件
file_candidates = glob.glob(f"{target_folder}/*_triang.dat")

2. 从文件名中提取时间并转为总秒数

你的文件名格式是xxx_时分秒_triang.dat(比如NIK_054504_triang.dat里的054504对应05小时、45分钟、04秒),我们把这个时间字符串转换成总秒数,这样排序就有了统一的数值依据:

def convert_time_to_seconds(file_name):
    # 拆分文件名,提取中间的6位时间字符串
    time_segment = file_name.split("_")[-2]
    # 拆分时分秒并计算总秒数
    hours = int(time_segment[:2])
    minutes = int(time_segment[2:4])
    seconds = int(time_segment[4:6])
    return hours * 3600 + minutes * 60 + seconds

如果担心文件名格式有变化,用正则表达式提取会更稳妥:

import re
def convert_time_to_seconds(file_name):
    # 匹配文件名里的6位数字时间部分
    time_match = re.search(r'(\d{6})_triang\.dat', file_name)
    if time_match:
        time_segment = time_match.group(1)
        hours = int(time_segment[:2])
        minutes = int(time_segment[2:4])
        seconds = int(time_segment[4:6])
        return hours * 3600 + minutes * 60 + seconds
    return 0  # 处理异常文件名的情况

3. 按时间排序文件列表并处理

用sorted()函数,把上面的转换函数作为排序依据,就能得到按时间顺序排列的文件列表了:

# 按时间从早到晚排序
sorted_file_list = sorted(file_candidates, key=convert_time_to_seconds)

# 如果需要从晚到早排序,加上reverse=True即可
# sorted_file_list = sorted(file_candidates, key=convert_time_to_seconds, reverse=True)

4. 遍历排序后的文件做后续处理

现在你可以放心地按时间顺序读取并处理每个文件了:

for file_path in sorted_file_list:
    print(f"正在处理:{file_path}")
    # 这里添加你的文件处理逻辑,比如读取dat文件内容
    with open(file_path, "r") as f:
        file_content = f.read()
        # 你的数据处理代码...

这样就能保证后续程序完全按照数据采集的时间顺序处理文件啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:47:27