【问题标题】:Replacing a line in a file using Python [duplicate]使用Python替换文件中的一行[重复]
【发布时间】:2013-09-21 11:49:01
【问题描述】:

我想用新行替换文件中的一行(实际上我必须在该行中插入一些内容)。该行实际上包含 AC_CONFIG_FILES([]) 我必须通过添加一些基于某些列表的 makefile 参数来将此行替换为新行。然后我构造了一个新字符串并在文件中进行了替换。有什么有效的方法吗?

# 'subdirs' is the list which contains makefile arguments
rstring = "AC_CONFIG_FILES([Makefile"
for t in subdirs:
    rstring = rstring+' src/'+t+'/Makefile'
rstring += '])'
print rstring
# 'fname' is the file in which replacement have to be done
#  i is used for indexing in 'insert' function
# 'rline' is the modified line
fname = 'configure.ac'
i = 0
with open(fname,'r') as f:
      modlines=[]
      for line in f.readlines():
          if 'AC_CONFIG_FILES' in line:
                  modlines.insert(i,rstring+'\n')
                  i = i+1
                  continue
          modlines.insert(i,line)
          i = i+1
with open(fname,'w') as out:
      for i in range(len(modlines)):
          out.write(modlines[i])

【问题讨论】:

  • 旁注:您的代码格式可以有效地改进:我建议您阅读并应用 PEP 8。此外,请注意不要像用 C 编写那样用 Python 编写:Python 代码比这个问题中的代码;例如,您通常不需要索引(请参阅 Johannes Charra 的回答)。

标签: python


【解决方案1】:

你可以在没有循环/计数器变量的情况下做到这一点

modlines = []
with open(fname) as f:
    for line in f:
        if 'AC_CONFIG_FILES' in line:
            modlines.append(rstring + '\n')
        else:
            modlines.append(line)

with open(fname, 'w') as out:
    for line in modlines:
        out.write(line)

【讨论】:

  • 你可以用out.write(''.join(modlines))替换你的第二个for
  • 这需要更多的内存。
  • 为什么投反对票?这个解决方案对我来说非常好。
  • 投反对票以阻止人们回答已经回答了数百次的重复问题。
猜你喜欢
  • 2020-07-21
  • 2014-06-28
  • 1970-01-01
  • 2013-05-13
  • 2013-11-01
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 2021-01-28
相关资源
最近更新 更多