使用Python替换文件中的行

时间:2013-09-17 06:51:05

标签: python

我想用新行替换文件中的一行(实际上我必须在行中插入一些内容)。该行实际上包含 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])

1 个答案:

答案 0 :(得分:3)

您可以在没有循环/计数器变量的情况下执行此操作

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)