不从主返回的值

我有以下代码,我希望将输入文件和输出文件拉入到其他函数中,但是,这些代码似乎没有返回。仍然很新,所以如果这很简单,请道歉。


# PYTHON 3.76 ONLY

# Version 0.0.1


import xml.etree.cElementTree as et

import pandas as pd


import sys, getopt


def main(argv):

    inputfile = ''

    outputfile = ''

    try:

        opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])

    except getopt.GetoptError:

        print ('test.py -i <inputfile> -o <outputfile>')

        sys.exit(2)

    for opt, arg in opts:

        if opt == '-h':

            print ('test.py -i <inputfile> -o <outputfile>')

            sys.exit()

        elif opt in ("-i", "--ifile"):

            inputfile = arg

        elif opt in ("-o", "--ofile"):

            outputfile = arg


    print ('Input file is "', inputfile)

    print ('Output file is "', outputfile)


    return inputfile, outputfile


if __name__ == "__main__":

    main(sys.argv[1:])


# convert XML to dataframe


def xml2df(xml_data):

    tree = et.parse(xml_data)

    print (tree.getroot())

    root = tree.getroot()

    print ("tag=%s, attrib=%s" % (root.tag, root.attrib))


    #iterate over each value for room and each user and add to rows

    rows = []


    for child in root.iter('rooms'):

        roomId, roomTitle = 'id', 'ttl'

    for it in child:

        if it.tag == 'room':

            roomId = it.findtext('roomID')

            roomTitle = it.findtext('roomTitle')

            roomStatus = it.findtext('status')

            isAnonymous = it.findtext('isAnonymous')


返回错误


回溯(最近调用最后):文件“parse_pChatDump.py”,第 63 行,在 df = xml2df(输入文件) 名称错误:未定义名称“输入文件”


慕斯709654
浏览 120回答 1
1回答

jeck猫

您在方法中创建和返回它,但是您不将它们存储在脚本开始的变量中,因此以后无法访问它们,请执行:inputfileoutputfilemaindef main(argv):&nbsp; &nbsp; inputfile = ''&nbsp; &nbsp; outputfile = ''&nbsp; &nbsp; # ...&nbsp; &nbsp; return inputfile, outputfiledef xml2df(xml_data):&nbsp; &nbsp; # ...&nbsp; &nbsp; return dfif __name__ == "__main__":&nbsp; &nbsp; inputfile, outputfile = main(sys.argv[1:])&nbsp; &nbsp; df = xml2df(inputfile)&nbsp; &nbsp; df.to_csv(outputfile + ".csv", sep=',', index=False)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python