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

前端 未结 2 901
鱼传尺愫
鱼传尺愫 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: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.

提交回复
热议问题