【问题标题】:How to write to a specific line in file in Python?如何在 Python 中写入文件中的特定行?
【发布时间】:2013-01-15 14:51:40
【问题描述】:

我有一个文件格式:

xxxxx
yyyyy
zzzzz
ttttt

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

xxxxx
my_line
yyyyyy
zzzzz
ttttt 

【问题讨论】:

标签: python python-2.7 io


【解决方案1】:
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)

【讨论】:

  • @mgilson 我不擅长 Python。我有C背景。如果在C 中提出问题,我要么在w+ 中打开文件,要么在r 中打开文件然后w 在Python 中只使用w 怎么办?
  • @GrijeshChauhan 'w' 在 python 中意味着创建一个新文件,或者如果已经存在则截断它。
  • @GrijeshChauhan -- open(filename,'w') 仅用于写作。以我在 C 方面的经验,文件模式非常相似。
  • @mgilson 好的,您正在从input 读取到output ..了解
  • @GrijeshChauhan -- 是的,在使用 ASCII 时,除非您想将整个文件读入内存,否则在原地完成这些事情相当困难......但即便如此,它也不是 真的到位。您只需将整个内容读入内存并使用相同的文件名将其写回...
【解决方案2】:

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

【讨论】:

  • 人们不能对 Python 束手无策。我的意思是,如果你在那里 ;)
猜你喜欢
  • 2013-06-13
  • 2014-10-05
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多