0

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

1 回答 1

4

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

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)
于 2013-09-17T06:58:57.887 回答