繁体   English   中英

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

[英]How to write to a specific line in file in Python?

我有一个文件作为格式:

xxxxx
yyyyy
zzzzz
ttttt

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

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

如果文件很小,则可以简单地使用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的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM