Skip to content

Instantly share code, notes, and snippets.

@detorto
Created May 31, 2017 11:49
Show Gist options
  • Save detorto/b38200dd08fdd0f756138fe59812ea51 to your computer and use it in GitHub Desktop.
Save detorto/b38200dd08fdd0f756138fe59812ea51 to your computer and use it in GitHub Desktop.
Replace plasehoders in xml by values from csv
#!/usr/bin/python
# coding: utf-8
import sys
from optparse import OptionParser
def sub_xml(data, fields, template, ofield):
print "Data :", data
for i,f in enumerate(fields):
template = template.replace(f,data[i])
return template, data[fields.index(ofield)]
def substitute(input_file, template, ofield):
ifile = open(input_file,"r")
fields = [f.strip() for f in ifile.readline().split(";")]
template = open(template).read()
print "Fields: ", fields
for i,line in enumerate(ifile.readlines()):
data = [d.strip() for d in line.split(";")]
res,fname = sub_xml(data, fields, template, ofield)
open(fname+".xml","w").write(res)
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-o", "--ofield", dest="ofield",
help="specify field for filename")
(options, args) = parser.parse_args()
input_file = args[0]
xml_template = args[1]
print "Input CSV: ", input_file
print "Xml template: ", xml_template
if not options.ofield:
print "Need to specify --ofield option"
sys.exit(1)
print "Outname field: ", options.ofield
substitute(input_file, xml_template, options.ofield)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment