我有以下代碼,我希望將輸入文件和輸出文件拉入到其他函數中,但是,這些代碼似乎沒有返回。仍然很新,所以如果這很簡單,請道歉。# PYTHON 3.76 ONLY# Version 0.0.1import xml.etree.cElementTree as etimport pandas as pdimport sys, getoptdef 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, outputfileif __name__ == "__main__": main(sys.argv[1:])# convert XML to dataframedef 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(輸入文件) 名稱錯誤:未定義名稱“輸入文件”
1 回答

jeck貓
TA貢獻1909條經驗 獲得超7個贊
您在方法中創建和返回它,但是您不將它們存儲在腳本開始的變量中,因此以后無法訪問它們,請執行:inputfileoutputfilemain
def main(argv):
inputfile = ''
outputfile = ''
# ...
return inputfile, outputfile
def xml2df(xml_data):
# ...
return df
if __name__ == "__main__":
inputfile, outputfile = main(sys.argv[1:])
df = xml2df(inputfile)
df.to_csv(outputfile + ".csv", sep=',', index=False)
添加回答
舉報
0/150
提交
取消