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和yyyyy\n之间插入一行。
另一种方法是编写一个函数来产生行,直到它看到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:
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)
这将在文件中每次出现
xxxxx\n
和yyyyy\n
之间插入一行。另一种方法是编写一个函数来产生行,直到它看到
xxxxx\nyyyyy\n
然后您可以使用这个直接传递给
writelines
:如果文件很小,那么您只需使用
str.replace()
:对于一个大文件,使用mgilson的方法。
相关问题 更多 >
编程相关推荐