如何在Python中写入文件中的特定行?(How to write to a specific line in file in Python?)
我有一个文件作为格式:
xxxxx
yyyyy
zzzzz
ttttt
我需要在xxxxx和yyyyy行之间写入文件:
xxxxx
my_line
yyyyyy
zzzzz
ttttt
I have a file as the format:
xxxxx
yyyyy
zzzzz
ttttt
And I need to write in file between xxxxx and yyyyy lines as:
xxxxx
my_line
yyyyyy
zzzzz
ttttt
原文:https://stackoverflow.com/questions/14340283
更新时间:2020-02-11 22:45
最满意答案
with open('input') as fin, open('output','w') as fout:
for line in fin:
fout.write(line)
if line == 'xxxxx\n':
next_line = next(fin)
if next_line == 'yyyyy\n':
fout.write('my_line\n')<