Skip to content

Instantly share code, notes, and snippets.

@dgroft
Last active December 18, 2015 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgroft/5733792 to your computer and use it in GitHub Desktop.
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
Copy link
Author

dgroft commented Jun 8, 2013

Added string format with positional arguments.

@dgroft
Copy link
Author

dgroft commented Jun 8, 2013

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
Copy link
Author

dgroft commented Jun 8, 2013

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

@dgroft
Copy link
Author

dgroft commented Jun 8, 2013

Removed unneeded print statement.

@dgroft
Copy link
Author

dgroft commented Jun 8, 2013

Fixed some tabbing issues.

@dgroft
Copy link
Author

dgroft commented Jun 9, 2013

Removed some unnecessary print statements.

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