Last active
December 18, 2015 05:38
-
-
Save dgroft/5733792 to your computer and use it in GitHub Desktop.
Converts CSV to XML in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.") |
Reading first line to grab headers. Also using with to auto-close the file, much in the same way that using() does in C#.
Parses CSV header row. Assembles a format string. Iterates each line, applying the format string, writing the result to the specified XML file.
Removed unneeded print statement.
Fixed some tabbing issues.
Removed some unnecessary print statements.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added string format with positional arguments.