输出文件仅包含一次迭代的数据

时间:2012-10-29 00:12:22

标签: python xml parsing for-loop elementtree

该脚本仅获取一个站的天气信息。我想获得链接中列出的所有内容,并将值写入下面脚本中格式的文件。

#! /usr/bin/python

#import module to open urls
from urllib import urlopen

#import module to parse xml
import xml.etree.ElementTree as ET

#settings
airport = 'KORF,KPHF,KRIC,KDCA,KIAD,KADW,KBWI,KACY,KPHL,KMDT,KPIT,KEWR,KJFK,KLGA,KBOS'

#open xml file
xml_link = urlopen('http://weather.aero/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=1&stationString=KORF,KPHF,KRIC,KDCA,KIAD,KADW,KBWI,KACY,KPHL,KMDT,KPIT,KEWR,KJFK,KLGA,KBOS')

#parse data and assign root to element tree module
tree = ET.parse(xml_link)
root = tree.getroot()

#search for data under <data> and <METAR> tags
data = root.findall('data/METAR')

for metar in data:
    raw_text = metar.find('raw_text').text
    station = metar.find('station_id').text
    category = metar.find('flight_category').text

    file = open('metar.txt', 'w')
    file.write("%s is now reporting %s condition:" % (station, category))
    file.write("\n%s" %raw_text)
    file.close()

1 个答案:

答案 0 :(得分:2)

this comment中所述,您的问题不在于如何迭代XML值,而在于每次循环时都覆盖metar.txt

您应该在循环外打开和关闭文件。 with声明可以帮助您,为您完成任务:

with open('metar.txt', 'w') as f:
    for metar in data:
        raw_text = metar.find('raw_text').text
        station = metar.find('station_id').text
        category = metar.find('flight_category').text

        f.write("%s is now reporting %s condition:" % (station, category))
        f.write("\n%s" %raw_text)

(您也不应该使用file作为文件对象的名称,因为file是文件对象的内置Python类型,如果这样做,您将会隐藏它。)