Skip to content

Instantly share code, notes, and snippets.

@dgroft
Last active December 18, 2015 05:38
Show Gist options
  • Select an option

  • Save dgroft/5733792 to your computer and use it in GitHub Desktop.

Select an option

Save dgroft/5733792 to your computer and use it in GitHub Desktop.
Converts CSV to XML in Python.
import argparse
import csv
parser = argparse.ArgumentParser(description="Converts a CSV file to an XML file")
parser.add_argument("csv", help="the path to the .CSV file")
parser.add_argument("xml", help="the path to the .XML file")
parser.add_argument("--root", help="root tag name", default="root")
parser.add_argument("--row", help="row tag name", default="row")
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
args = parser.parse_args()
if args.verbose:
print("Beginning CSV to XML conversion ...")
with open(args.csv, "r") as csvFile:
reader = csv.reader(csvFile)
headers = next(reader)
# column0="{0}" column1="{1}" column2="{2}"
attributesFormat = " ".join("{0}=\"{{{1}}}\"".format(val, idx) for idx, val in enumerate(headers))
# "<row .../>"
rowFormat = "<{0} {1}/>".format(args.row, attributesFormat)
with open(args.xml, "w") as xmlFile:
print("<{0}>".format(args.root), file=xmlFile) # <root> node
for line in reader:
print(rowFormat.format(*line), file=xmlFile) # <row/> node(s)
print("</{0}>".format(args.root), file=xmlFile) # </root> node
if args.verbose:
print("CSV to XML conversion complete.")
@dgroft

dgroft commented Jun 8, 2013

Copy link
Copy Markdown
Author

Reading first line to grab headers. Also using with to auto-close the file, much in the same way that using() does in C#.

@dgroft

dgroft commented Jun 8, 2013

Copy link
Copy Markdown
Author

Parses CSV header row. Assembles a format string. Iterates each line, applying the format string, writing the result to the specified XML file.

@dgroft

dgroft commented Jun 8, 2013

Copy link
Copy Markdown
Author

Removed unneeded print statement.

@dgroft

dgroft commented Jun 8, 2013

Copy link
Copy Markdown
Author

Fixed some tabbing issues.

@dgroft

dgroft commented Jun 9, 2013

Copy link
Copy Markdown
Author

Removed some unnecessary print statements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment