How to write to a specific line in file in Python?

前端 未结 2 879
鱼传尺愫
鱼传尺愫 2021-01-06 04:35

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         


        
相关标签:
2条回答
  • 2021-01-06 05:12
    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)
    

    This will insert your line between every occurrence of xxxxx\n and yyyyy\n in the file.

    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
    

    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)
    
    0 讨论(0)
  • 2021-01-06 05:33

    If the file is small then you can simply use 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
    

    For a huge file use mgilson's approach.

    0 讨论(0)
提交回复
热议问题