【发布时间】:2021-04-09 02:21:11
【问题描述】:
我正在编写我的第一个 Python 脚本。我有它的工作,但我很肯定有更好的方法来做到这一点。该脚本从文本文件中获取 5 个城市的列表,并将其输出到 CSV,其中包括城市名称、最低温度、最高温度、温度和日落时间。我的脚本正好查找 5 个城市,不多也不少。我将如何更改它以搜索任意数量的城市?
这是我的脚本:
import requests
import csv
with open("cities.txt") as file:
city1 = file.readline().replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city1)
res = requests.get(url)
data = res.json()
temp_min1 = data['main']['temp_min']
temp_max1 = data['main']['temp_max']
sunset1 = data['sys']['sunset']
with open("cities.txt") as file:
city2 = file.readlines()[1].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city2)
res = requests.get(url)
data = res.json()
temp_min2 = data['main']['temp_min']
temp_max2 = data['main']['temp_max']
sunset2 = data['sys']['sunset']
with open("cities.txt") as file:
city3 = file.readlines()[2].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city3)
res = requests.get(url)
data = res.json()
temp_min3 = data['main']['temp_min']
temp_max3 = data['main']['temp_max']
sunset3 = data['sys']['sunset']
with open("cities.txt") as file:
city4 = file.readlines()[3].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city4)
res = requests.get(url)
data = res.json()
temp_min4 = data['main']['temp_min']
temp_max4 = data['main']['temp_max']
sunset4 = data['sys']['sunset']
with open("cities.txt") as file:
city5 = file.readlines()[4].replace('\n', '')
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=01f5be003452b3ef921c3d00296365d9&units=imperial'.format(city5)
res = requests.get(url)
data = res.json()
temp_min5 = data['main']['temp_min']
temp_max5 = data['main']['temp_max']
sunset5 = data['sys']['sunset']
outputFile = open('output.csv', 'w', newline='')
outputWriter = csv.writer(outputFile)
outputWriter.writerow([city1,temp_min1,temp_max1,sunset1,city2,temp_min2,temp_max2,sunset2,city3,temp_min3,temp_max3,sunset3,city4,temp_min4,temp_max4,sunset4,city5,temp_min5,temp_max5,sunset5,])
outputFile.close()
【问题讨论】:
标签: python python-3.x csv