如何以最简洁的Pythonic方式重构日期关联的TXT文件格式?
实现日志格式重构的简洁Python方案
问题说明
输入文件内容如下:
27/04/2023 00:00 0.1 06:00 0.5 23:00 0.9 28/04/2023 00:00 0.1 06:00 0.5 23:00 0.9 29/04/2023 00:00 0.1 06:00 0.5 23:00 0.9
期望转换为如下格式:
27/04/2023 00:00 0.1 27/04/2023 06:00 0.5 27/04/2023 23:00 0.9 28/04/2023 00:00 0.1 28/04/2023 06:00 0.5 28/04/2023 23:00 0.9 29/04/2023 00:00 0.1 29/04/2023 06:00 0.5 29/04/2023 23:00 0.9
当前实现步骤为:
- 逐行读取文件
- 判断行是否为日期,存储行号和日期到对应列表
- 获取连续日期的行号对,截取中间内容并插入对应日期
但现有代码臃肿,且无法处理文件最后一天的数据:
from datetime import datetime data_file = 'data.txt' dates = [] dates_line_number = [] with open(data_file) as input_file: for i, line in enumerate(input_file): # 仅读取日期行,存储行号和日期 try: date_object = datetime.strptime(line.strip(), '%d/%m/%Y') dates.append(date_object) dates_line_number.append(i) del date_object except: pass file = open(data_file) content = file.readlines() i = 0 f = open("outfile.txt", "w") for index in range(len(dates_line_number)): # 获取连续日期的行号对 ls_index = dates_line_number[index:index+2] if len(ls_index) == 2: start = ls_index[0]+1 end = ls_index[1]-1 # 截取连续日期行号间的内容 ls_out = (content[start:end+1]) # 插入对应日期字符串 str_date = f"{dates[i].strftime('%d/%m/%Y')} " ls_out.insert(0, '') str_out = str_date.join(ls_out) f.write(str_out) i = i+1 f.close()
最简洁Pythonic实现
只需要一次遍历文件,维护当前日期变量即可,代码如下:
input_path = 'data.txt' output_path = 'outfile.txt' current_date = None with open(input_path, 'r') as infile, open(output_path, 'w') as outfile: for line in infile: line = line.strip() if not line: continue # 跳过空行 # 判断是否为日期行(通过格式匹配) if len(line.split('/')) == 3: current_date = line else: # 拼接日期和时间行,写入输出文件 outfile.write(f"{current_date} {line}\n")
实现思路
- 初始化
current_date变量存储当前处理的日期 - 同时打开输入和输出文件,逐行读取输入内容
- 遇到符合
dd/mm/yyyy格式的行(通过斜杠分割后的元素数量判断),更新current_date - 遇到时间数据行时,直接拼接
current_date和当前行内容,写入输出文件 - 自动跳过空行,避免无效内容
优势
- 内存高效:无需一次性读取整个文件到内存,适合处理大文件
- 代码简洁:逻辑清晰,行数少,符合Pythonic风格
- 无边界问题:自然处理最后一天的数据,无需额外判断行号区间
内容的提问来源于stack exchange,提问作者PaulR
相关产品推荐
相关产品推荐

