如何在Python中写入文件中的特定行?

时间:2013-01-15 14:51:41

标签: python python-2.7 io

我有一个文件格式:

xxxxx
yyyyy
zzzzz
ttttt

我需要在xxxxx和yyyyy行之间写入文件:

xxxxx
my_line
yyyyyy
zzzzz
ttttt 

2 个答案:

答案 0 :(得分:3)

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\nyyyyy\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)

答案 1 :(得分:3)

如果文件很小,那么您只需使用str.replace()

>>> !cat abc.txt
xxxxx
yyyyy
zzzzz
ttttt

>>> with open("abc.txt") as f,open("out.txt",'w') as o:
    data=f.read()
    data=data.replace("xxxxx\nyyyyy","xxxxx\nyourline\nyyyyy")
    o.write(data)
   ....:     

>>> !cat out.txt
xxxxx
yourline
yyyyy
zzzzz
ttttt

对于一个巨大的文件使用mgilson的方法。