我的文本文件如下:
0211111
aaaaaaaa
bbbbbbbb
ccccccccc
02333333
ddddddd
eeeeeeeee
fffffff
02444444
ggggggg
fffffff
jjjjjjjj
0211111
kkkkkkkk
llllllll
mmmmmmm
02333333
ggggggg
fffffff
jjjjjjjj
我读取从02开始的文本行,并希望从每次开始复制到3个新文件(0211111.txt
、02333333.txt
、02444444.txt
)行
021*
,023*
,024*
直到模式出现02
再次出现,不包括此行,复制直到行[i-1]
。你知道吗
生成的文件输出如下。你知道吗
0211111.txt文件
0211111
aaaaaaaa
bbbbbbbb
ccccccccc
0211111
kkkkkkkk
llllllll
mmmmmmm
0233333.txt文件
02333333
ddddddd
eeeeeeeee
fffffff
02333333
ddddddd
eeeeeeeee
fffffff
024444.txt文件
02444444
ggggggg
fffffff
jjjjjjjj
我已经编写了下面的python脚本,但它并没有像预期的那样工作,因为它采用了023*
模式下面的行并复制到新文件0211111.txt
。你知道吗
f1 = open("C:\\..\\..merge_d.txt")
f2 = open("C:\\..\\..\\newf_021.txt", 'a')
f3 = open("C:\\..\\..\\newf_023.txt", 'a')
f4 = open("C:\\..\\..\\newf_024.txt", 'a')
f2.truncate(0)
f3.truncate(0)
f4.truncate(0)
global lines_nums_021
lines_nums_021 = []
global i_x_021
i_x_021 = 0
cache_021 = []
output_data_021 = []
for i,line in enumerate(lines,1):
find_n = line.startswith("021")
lines_nums_n.append((find_021, i))
# lines_nums_M.append((find_023, i))
# lines_nums_C.append((find_024, i))
i_x_021=next(v[1] for v in lines_nums_n if v[0] is True)
# i_x_M=next(v[1] for v in lines_nums_023 if v[0] is True)
# i_x_C=next(v[1] for v in lines_nums_024 if v[0] is True)
for i,line in enumerate(lines,1):
if line.startswith("021"):
cache_021.append(line)
elif not line.startswith("021") and i >= i_x_021:
output_data_021.extend(cache_021)
output_data_021.append(line)
cache_021 = []
for item in output_data_n:
f2.write("%s" % item)
print (i_x_021)
我不知道你为什么要做所有的缓存等,但这应该可以做到:
希望这会有所帮助。下面的代码为每个要写出的文件创建一个字典,匹配的模式作为键。然后根据需要在文件指针之间切换。你知道吗
相关问题 更多 >
编程相关推荐