如何在Python中写入文件中的特定行? [英] How to write to a specific line in file in Python?
本文介绍了如何在Python中写入文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个格式的文件:
xxxxx
yyyyy
zzzzz
ttttt
我需要在xxxxx和yyyyy行之间写入文件:
And I need to write in file between xxxxx and yyyyy lines as:
xxxxx
my_line
yyyyyy
zzzzz
ttttt
推荐答案
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')
fout.write(next_line)
这将在每次出现 xxxxx \ n <之间插入您的行/ code>和文件中的
yyyyy \ n
。
另一种方法是写在看到 xxxxx \\\
yyyyy之前产生线的函数\\ n
An alternate approach would be to write a function to yield lines until it sees an xxxxx\nyyyyy\n
def getlines(fobj,line1,line2):
for line in iter(fobj.readline,''): #This is necessary to get `fobj.tell` to work
yield line
if line == line1:
pos = fobj.tell()
next_line = next(fobj):
fobj.seek(pos)
if next_line == line2:
return
然后你可以使用这个直接传递给 writelines
:
Then you can use this passed directly to writelines
:
with open('input') as fin, open('output','w') as fout:
fout.writelines(getlines(fin,'xxxxx\n','yyyyy\n'))
fout.write('my_line\n')
fout.writelines(fin)
这篇关于如何在Python中写入文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文