使用Python为txt文件添加递增时间戳并拆分文本块的方法
文本块添加递增时间戳并拆分存储实现方案
需求说明
- 待处理txt文件中存储了多组结构化文本块,块与块之间以空行分隔,每个块末尾的
timestamp::字段为空 - 需要为每个块填充逐次递增1秒的时间戳,填充完成后将每个块单独保存为独立的txt文件
原始文本示例
name:: Joe Blogs phone:: 123456789 email:: joeblogs@email.com address:: 123 Main Street note:: blah blah blah timestamp:: name:: Josephine Blogs phone:: 43217890 email:: josephineblogs@email.com address:: 123 Main Street note:: More blah blah timestamp:: name:: John Smith phone:: 23498689 email:: johnsmith@email.com address:: 1 North Street note:: Some more blah timestamp::
预期处理效果
name:: Joe Blogs phone:: 123456789 email:: joeblogs@email.com address:: 123 Main Street note:: blah blah blah timestamp:: 2022-07-15 (14h 55m 23s) name:: Josephine Blogs phone:: 43217890 email:: josephineblogs@email.com address:: 123 Main Street note:: More blah blah timestamp:: 2022-07-15 (14h 55m 24s) name:: John Smith phone:: 23498689 email:: johnsmith@email.com address:: 1 North Street note:: Some more blah timestamp:: 2022-07-15 (14h 55m 25s)
原有代码问题排查
原有代码运行不符合预期,核心问题有三个:
- 逐行遍历完文件后,文件指针已经移动到文件末尾,后续调用
f.read()只能读取到空内容,自然无法正确拆分块 - 循环内修改
line变量只是修改临时变量,改动不会写入原文件,也不会被后续逻辑读取到 - 用
time.sleep(1)等待1秒获取下一个时间戳效率极低,完全不需要真实等待,直接基于初始时间做秒级偏移计算即可得到对应时间戳
可直接运行的实现代码
from datetime import datetime, timedelta # 可自行修改初始时间为需要的起始值 start_timestamp = datetime.now() # 一次性读取全部文件内容 with open('file.txt', 'r', encoding='utf-8') as f: raw_content = f.read() # 按空行拆分出所有有效文本块 chunk_list = [chunk.strip() for chunk in raw_content.split('\n\n') if chunk.strip()] for chunk_index, chunk in enumerate(chunk_list): # 第n个块对应偏移n秒,无需等待直接计算时间 current_time = start_timestamp + timedelta(seconds=chunk_index) format_time = current_time.strftime('%Y-%m-%d (%Hh %Mm %Ss)') # 替换空的时间戳字段 processed_chunk = chunk.replace('timestamp::', f'timestamp:: {format_time}') # 写入独立的块文件 with open(f'chunk_{chunk_index + 1}.txt', 'w', encoding='utf-8') as out_f: out_f.write(processed_chunk) # 可选:将添加完时间戳的完整文本保存为新文件,方便校验 with open('file_with_timestamp.txt', 'w', encoding='utf-8') as f: full_content = [] for i, chunk in enumerate(chunk_list): ts = (start_timestamp + timedelta(seconds=i)).strftime('%Y-%m-%d (%Hh %Mm %Ss)') full_content.append(chunk.replace('timestamp::', f'timestamp:: {ts}')) f.write('\n\n'.join(full_content))
逻辑说明
- 采用一次性读取全量内容的方式,避免文件指针移动导致的读取为空问题
- 时间戳通过时间偏移计算生成,处理上百个块也不需要额外等待,执行效率高
- 拆分块时自动过滤空内容,避免因文件首尾空行、多余空行生成无效的空文件
- 编码统一指定为utf-8,避免不同系统下打开文件出现乱码
内容的提问来源于stack exchange,提问作者supposer
相关产品推荐
相关产品推荐

