import re
output = open("teste-out.txt","w")
input = open("teste.txt")
for line in input:
output.write(re.sub(r"\n\r03110", r"|03110", line))
input.close()
output.close()
为什么此代码无法正常工作,任何人都可以帮助我修复它?我想从txt中读取内容,如果该行以03110
开头,我只想将此行与上一行合并,并在合并前添加|
我尝试过\n03110
\r03110
和其他选项,但是没有一个起作用。在notepad ++中,我可以使用\R++03110
进行此操作,并使用正则表达式替换为|03110
,但我想使用python解决方案来优化工作。
输入
01000|0107160
02000|1446
03100|01|316,00
03110|||316,00|0|0|7|
03100|29|135,00
03110|||135,00|0|0|0|
99999|83
00000|00350235201512001|01071603100090489
输出
01000|0107160
02000|1446
03100|01|316,00|03110|||316,00|0|0|7|
03100|29|135,00|03110|||135,00|0|0|0|
99999|83
00000|00350235201512001|01071603100090489
我在Windows上使用python。
仅针对感兴趣的情况-这不是re
工作恕我直言:
s_in = '''01000|0107160
02000|1446
03100|01|316,00
03110|||316,00|0|0|7|
03100|29|135,00
03110|||135,00|0|0|0|
99999|83
00000|00350235201512001|01071603100090489'''
from io import StringIO
with StringIO(s_in) as fin:
for line in fin:
if line.startswith('03100'):
print(line[:-1] + '|' + next(fin), end='')
else:
print(line, end='')
要求的结果
01000|0107160
02000|1446
03100|01|316,00|03110|||316,00|0|0|7|
03100|29|135,00|03110|||135,00|0|0|0|
99999|83
00000|00350235201512001|01071603100090489
非常简短的sed
解决方案(效率不高,因为它在打印任何内容之前都会读取所有行):
< input_file sed '$!N;s/\n03110/03110/g'