Note that there are some explanatory texts on larger screens.

plurals
  1. POChanging file extensions using argparse in python
    primarykey
    data
    text
    <p>I want to change the file extensions of a given csv file to a xml extension or vice versa. At the command line, i can input the following</p> <pre><code>Boo a.csv. giving a.xml Boo a.xml. giving a.csv Boo a.csv -out shoes.xml giving shoes.xml </code></pre> <p>here is my updated code:</p> <pre><code>import os import sys import argparse import csv import indent from xml.etree.ElementTree import ElementTree, Element, SubElement, Comment, tostring def get_args(args): parser = argparse.ArgumentParser(description = "Converts CSV to XML") parser.add_argument('-v','--verbose',action='store_true',dest='verbose',help='Increases messages being printed to stdout') parser.add_argument("inputfile", help="Please input the name of the CSV file") parser.add_argument('-o','--outputfile',help='(optional) Output file name',nargs='?') args = parser.parse_args() ext = os.path.splitext(args.inputfile)[1].lower() if args.outputfile is None: if ext == ".csv": args.outputfile = os.path.splitext(args.inputfile)[0] + '.xml' elif ext == ".xml": args.outputfile = os.path.splitext(args.inputfile)[0] + '.csv' else: sys.stderr.write('ERROR: Invalid extension %s\n' % ext) sys.exit(1) return args def main(argv): args = get_args(argv[0:]) if args is None: return 1 reader = read_csv(args.inputfile) if args.verbose: print ('Verbose Selected') if args.verbose: print ('Convert to XML with set name') generate_xml(reader, args.outputfile) return 0 def read_csv(inputfile): return list(csv.reader(inputfile)) def generate_xml(reader,outfile): root = Element('Solution') root.set('version','1.0') tree = ElementTree(root) head = SubElement(root, 'DrillHoles') description = SubElement(head,'description') current_group = None i = 0 for row in reader: if i &gt; 0: x1,y1,z1,x2,y2,z2,cost = row if current_group is None or i != current_group.text: current_group = SubElement(description, 'hole',{'hole_id':"%s"%i}) collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}), toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))}) cost = SubElement(current_group, 'cost',{'':cost}) i+=1 head.set('total_holes', '%s'%i) indent.indent(root) tree.write(outfile) if (__name__ == "__main__"): sys.exit(main(sys.argv)) </code></pre> <p>Now i get an error at x1,y1,z1,x2,y2,z2,cost = row and it is a value error that says: need more than one value to unpack</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload