如何用Python将.txt文件中每对括号内的内容单独保存?
问题描述
我有一个txt文件,内容格式如下:
[ "8.782897907000063,1.718493196000054", "8.782768250000061,1.718278646000044", "8.78276825100005,1.718376662000026" ] [ "8.78288150700007,1.718478835000042", "8.782897907000063,1.718493196000054" ] [...... (还有4000多组...)
我需要把每一对[]包裹的内容单独保存成一个文件,每个新文件的内容示例如下:
[ "8.782897907000063,1.718493196000054", "8.782768250000061,1.718278646000044", "8.78276825100005,1.718376662000026" ]
我已经知道如何按行保存文件(代码如下),但不知道怎么实现按括号拆分保存的需求,请问用Python该怎么做?
附按行保存的代码:
infile = 'file_name.txt' with open(infile, 'r') as f: lines = f.readlines() counter = 1 for line in lines: if line outfile = 'file_name' + str(counter) + '.txt' with open(outfile, 'w') as g: g.write(line) counter += 1
解决方案
可以通过跟踪括号的开闭状态,逐行收集每组数组的内容,当遇到闭合的]时,将收集到的内容写入新文件,具体代码如下:
infile = 'file_name.txt' counter = 1 current_group = [] in_group = False with open(infile, 'r', encoding='utf-8') as f: for line in f: stripped_line = line.strip() # 遇到开括号,开始收集当前组内容 if stripped_line == '[': in_group = True current_group.append(line) # 遇到闭括号,结束当前组收集并写入文件 elif stripped_line == ']': in_group = False current_group.append(line) # 写入文件 outfile = f'group_{counter}.txt' with open(outfile, 'w', encoding='utf-8') as g: g.writelines(current_group) # 重置当前组,计数器加1 current_group = [] counter += 1 # 处于组内时,收集行内容 elif in_group: current_group.append(line) print(f"共生成 {counter-1} 个文件")
代码说明
in_group标记是否正在收集某一组的内容- 每遇到
[就开启收集模式,把该行加入current_group - 每遇到
]就关闭收集模式,把该行加入后,将整个current_group写入新文件,然后重置收集列表并递增计数器 - 组内的行直接加入收集列表,保留原格式
内容的提问来源于stack exchange,提问作者Tommy
相关产品推荐
相关产品推荐

