Find and replace multiple strings in file then output to new filename python
I am looking to create a python script that will read one source file then produce another file with a string for the name.
for example
macaddress.cnf.xml contains the source file
I need to change '6000' to '6001' in multiple places of macaddress.cnf.xml, then I want to output to newmacaddress.cnf.xl开发者_Go百科.
This is what I have
#! /usr/bin/python
#read and write to file
f = open(file)
for line in f:
if line.contains('66001'):
newline = line.replace('66001', '60001')
To add I would like to be able to do this with a csv or whatever and have the script run through and do
60002 >> macaddressfromcsv.cnf.xml 60003 >> macaddressfromcsv.cnf.xml 60004 etc.
Sorry I am very new to this any help would be great.
It is unclear from your question what all of your goals are, but I will try to address some of them. If you want to take input from one file, modify it, and then write to another file you could do following:
buffer = "";
with open("input_file") as in:
buffer = in.read();
# do modifications ...
with open("output_file", 'w') as out:
out.write(buffer);
Note: you would need to use from __future__ import with_statement
in python version 2.5.
To do multiple replacements you can actually use re.sub()
function:
buffer = re.sub('6000', '6001', buffer)
As to the the additional information using csv, please provide a more detailed explanation or an example of what you are trying to achieve.
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()
Edit. I think you need to clarify the question. Is there only one output file or to you want one file per replacement?
精彩评论