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

bar*_*arp 6 python io python-2.7

我有一个文件格式:

xxxxx
yyyyy
zzzzz
ttttt
Run Code Online (Sandbox Code Playgroud)

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

xxxxx
my_line
yyyyyy
zzzzz
ttttt 
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 4

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)
Run Code Online (Sandbox Code Playgroud)

这将在文件中每次出现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
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它直接传递到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)
Run Code Online (Sandbox Code Playgroud)

  • @GrijeshChauhan - 是的,在使用 ASCII 时,除非您想将整个文件读入内存,否则很难就地完成这些操作……但即便如此,它也不是“真正”到位。您只需将整个内容读入内存并使用相同的文件名将其写回... (2认同)