【发布时间】: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