在python中使用argparse更改文件扩展名

时间:2013-06-18 15:37:27

标签: python xml csv argparse

我想将给定csv文件的文件扩展名更改为xml扩展名,反之亦然。在命令行,我可以输入以下内容

Boo a.csv.                   giving   a.xml
Boo a.xml.                   giving   a.csv
Boo a.csv -out shoes.xml     giving   shoes.xml

这是我更新的代码:

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 > 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))

现在我在x1,y1,z1,x2,y2,z2,cost = row时出现错误,这是一个值错误,表示:需要多个值才能解压缩

1 个答案:

答案 0 :(得分:0)

问题是您没有将扩展名分配给 ext 。扩展名是splitext返回的第二个项目。当ext既不是.xml也不是.csv时,你还应该有另一个条件。此错误路径会向您显示问题。

编辑:您的代码还有其他问题,所以我添加了一些标记为TODO的注释。您不应该将参数解析与程序的实现混合在一起。所以,在你清理了你的论点后,你应该在你调用的地方使用tree.whatever()。你会发现你只需要在最后调用tree.whatever()一次。

import argparse
import os
import sys
import csv
from xml.etree.ElementTree import ElementTree, Element, SubElement

parser = argparse.ArgumentParser(description = "Converts CSV to XML")
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'
        tree.write(args.outputfile) # TODO: There is no 'tree' defined
    elif ext == ".xml":
        args.outputfile = os.path.splitext(args.inputfile)[0] + '.csv'
        tree.write(args.outputfile) # TODO: There is no 'tree' defined
    else:
        sys.stderr.write('ERROR: Invalid extension %s\n' % ext)
        sys.exit(1)

# TODO: This should be removed completely
if args.outputfile:
    args.outputfile = os.path.splitext(args.outputfile)[1] #handles the condition if there is an outputfile set by the user
# TODO: create tree and do the work here