需要编码CSV文件的指南

时间:2017-04-07 06:19:32

标签: python-3.x csv

现在,我有代码它从网站解析XML

    def Value2():
for station in tree.findall('./stations/'):
    if station.tag == 'station':
        for item1 in station:
            if  item1.tag == 'stationID':  
                print(item1.tag, item1.text)
                wf.writerow([item1.text])   ###need guide
        for item2 in station:
            if  item2.tag == 'nameTH': 
                print(item2.tag, item2.text)
                wf.writerow([item2.text])  ###need guide
        for item3 in station:
            if  item3.tag == 'nameEN':
                print(item3.tag, item3.text)  
        for item4 in station:
            if  item4.tag == 'areaTH':         
                print(item4.tag, item4.text)
        for item5 in station:
            if  item5.tag == 'areaEN':         
                print(item5.tag, item5.text)
        for item6 in station:
            if  item6.tag == 'stationtype':
                print(item6.tag, item6.text)
        for item7 in station:
            if  item7.tag == 'lat':
                print(item7.tag, item7.text)
   wf.writerow([item1.text],[item2.text],[item3.text])   ###try to test

   dates = time.strftime("%Y%m%d")
   outpath = r"C:\Users\Gistda59\Desktop\Test" + "\\" + dates
   if not os.path.exists(outpath):
     os.makedirs(outpath)
   f = open(outpath + "\\" + "pm10daily-" + dates + ".csv","w",newline='')
   wf = csv.writer(f)
wf.writerow (["stationID","nameTH","nameEN","areaTH","areaEN","stationtype","latitude","longitude","date","time","PM10","O3","NO2","SO2","AQI"])
print ("\n\t\t***** XML TO CSV ON air4thai*****\n")
Air4thaiURL = 'http://air4thai.pcd.go.th/services/getAQI_XML.php?region=2' 
### URL ###
resp = requests.get(Air4thaiURL)
msg = resp.content
tree = ET.fromstring(msg)
Value1()
Value2()

f.close()

但是现在我需要指南来写入CSV,它似乎写在第一列而不是写入其他列。但我会尝试这样的

 wf.writerow([item1.text],[item2.text],[item3.text])

来自代码

它无效。我需要这样的 OUTPUT CSV 请求帮助和指导。

0 个答案:

没有答案