在文件中查找替换多个字符串并输出到新文件名的Python代码
我想写一个Python脚本,它可以读取一个源文件,然后生成另一个文件,文件名是一个字符串。
举个例子:
macaddress.cnf.xml是我的源文件。
我需要把macaddress.cnf.xml里面的'6000'改成'6001',而且这个改动要在多个地方进行。然后我想把结果输出到一个叫做newmacaddress.cnf.xml的新文件里。
这是我现在有的代码:
#! /usr/bin/python
#read and write to file
f = open(file)
for line in f:
if line.contains('66001'):
newline = line.replace('66001', '60001')
另外,我还希望能够用一个CSV文件或者其他格式来实现这个功能,让脚本自动处理。
比如说:
60002 >> macaddressfromcsv.cnf.xml
60003 >> macaddressfromcsv.cnf.xml
60004等等。
抱歉,我对这些还很陌生,任何帮助都非常感谢。
2 个回答
0
data=open("input_file").read()
outfile=open("macaddressfromcsv.cnf.xml","w")
for i in range(6001,6010):
outfile.write(data.replace("6000",str(i))
outfile.write("\n") # you may not need this
outfile.close()
编辑一下。我觉得你需要把问题说清楚。你是想要一个输出文件,还是每次替换都想要一个文件呢?
1
从你的问题中不太清楚你具体想要达到什么目标,但我会尽量帮你解答一些。假如你想从一个文件读取内容,修改后再写入另一个文件,你可以这样做:
buffer = "";
with open("input_file") as in:
buffer = in.read();
# do modifications ...
with open("output_file", 'w') as out:
out.write(buffer);
注意:如果你使用的是Python 2.5版本,你需要在代码中加上 from __future__ import with_statement
。
如果你想进行多次替换,其实可以使用 re.sub()
这个函数:
buffer = re.sub('6000', '6001', buffer)
至于使用csv的额外信息,请提供更详细的解释或者你想要实现的例子。