Python循环读取多文件数据如何将所有结果合并为同一列表
问题根源
你的代码每次循环都在内部重新初始化jValuesList2 = [],每次迭代都会创建全新的空列表,之前循环存入的内容会被直接覆盖,循环结束后自然只保留最后一个文件的处理结果。另外原代码存在缩进错误、同一文件重复打开读取、路径拼接兼容性差的问题,也一并修正。
修改方案
- 在for循环外部提前初始化总结果列表,整个循环过程中不会被重置
- 单个文件的数据提取完成后,将单文件结果追加到总列表中,保留所有历史数据
- 修正缩进错误,合并重复的文件读取操作,用标准库方法拼接路径避免跨系统兼容问题
- 所有文件处理完成后,遍历总列表写入txt文件即可
修改后完整代码
import os # 替换为你的.ls文件所在目录路径 path = "目标文件夹路径" # 循环外初始化总列表,存储所有文件的提取结果 all_result = [] for file in os.listdir(path): if file.endswith(".ls"): # 标准路径拼接,兼容Windows/macOS/Linux filepath = os.path.join(path, file) # 单次打开文件读取所有行,无需重复打开两次 with open(filepath, 'r', encoding='utf-8') as f: all_lines = f.readlines() # 提取日期字段 date_line = all_lines[3:4][0] numericalDate = ' '.join([date_line])[10:20] # 提取J值相关行 j_lines = all_lines[43:53] jValuesList = [ j_lines[3], j_lines[4], j_lines[5], j_lines[6], j_lines[7], j_lines[8], j_lines[9] ] jValuesJoin = ' '.join(jValuesList) # 按位置截取目标数值 j1Values = jValuesJoin[10:16] j2Values = jValuesJoin[51:57] j3Values = jValuesJoin[92:98] j4Values = jValuesJoin[133:139] j5Values = jValuesJoin[174:180] j6Values = jValuesJoin[215:221] j7Values = jValuesJoin[256:262] # 组装单个文件的结果 single_file_data = [ numericalDate, j1Values, j2Values, j3Values, j4Values, j5Values, j6Values, j7Values ] # 将单文件结果追加到总列表,不会覆盖之前的数据 all_result.append(single_file_data) # 所有文件处理完成后,将总结果写入txt with open("提取结果.txt", "w", encoding="utf-8") as out_f: for row in all_result: # 用制表符分隔各字段,可直接用Excel打开 out_f.write("\t".join(row) + "\n")
效果说明
循环全部执行完成后,all_result是二维列表,每个子元素对应一个.ls文件提取的8个字段,写入文件时会包含所有文件的处理结果,不会再出现仅保存最后一批数据的问题。
内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

