如何将 for 循环的内容保存到 python 中的文本文件

How do I save the contents of a for loop to a text file in python

我叫斯科特·莱因哈特。我一直在研究一个程序,该程序从 NWS 当前的 rss 数据提要中获取当前的天气状况。该程序生成每三个字母的可能性,然后循环遍历每种可能性,将其插入 rss url 以查看它是否调出有效页面。如果是,它会解析温度、湿度和露点值。我成功地让程序解析所有有效机场代码的温度湿度和露点,但我不知道如何将所有这些数据保存到文本文件中。

这是我的代码:

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor)
opener.addheaders = [('User-agent','mr_anderson')]


keywords = map(''.join, product(ascii_lowercase, repeat=3))
keywords = ["k"+a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]

start_time = time.time()

print("--- %s seconds ---" % (time.time() - start_time))

    try:
        a = 1
        b = 1
        for i in range (1,20):
            i=1
            i+=1
            a+=1
            b+=1
            keywargs = str(keywords[a]).upper()
            argument = 'http://w1.weather.gov/xml/current_obs/'+keywargs+'.rss'
            req = Request(argument)
            try:
                page_open = urlopen(req)
            except:
                None

        else:

            c=1
            c+=1
            sourceCode = opener.open(argument).read()
            tempraw = re.findall(r'and\s\d{1,2}\s\w.*?',str(sourceCode))
            windraw = re.findall(r'at\s\d{1,2}\.\d{0,1}.*?',str(sourceCode))
            pressureraw = re.findall(r'The pressure is\s\d{1,4}\.\d{0,1}\s\w\w.*?',str(sourceCode))
            humidraw = re.findall(r'the humidity is\s\d{1,2}\%.*?',str(sourceCode))
            temp = tempraw[0]
            temprevised = str(temp).strip("[and F]")
            print(temprevised)
            text_file = open("nws_contourcurrenttemp_data.txt","w")
            text_file.write(temprevised)
            print(str(temp)+' '+keywargs+str(windraw)+str(pressureraw)+str(humidraw))


except Exception, e:
    print(str(e))



print("--- %s seconds ---" % (time.time() - start_time))

当我打印所有这些数据时,一切都像预期的那样工作,但它只会打印文本文件中的一行数据。我不明白这是为什么。

谢谢,

斯科特·莱因哈特

当您应该使用附加模式 a 时,您正在使用 w 以写入模式打开文件,如下所示:

text_file = open("nws_contourcurrenttemp_data.txt","a")

解释一下,模式w用于当你想完全覆盖文件时写入。当您调用它时,所有内容都将被删除。 a 用于追加,将信息添加到文件末尾,不会删除文件中当前的任何信息。

您正在打开的文件的路径似乎是不变的,因此您在循环中一遍又一遍地重新打开同一个文件。尝试只在循环之外打开文件一次。