python - 在Python中读取文件

标签 python weather

好吧,我在 python 中有一个命令可以写入文件

 from urllib.request import urlretrieve
urlretrieve('http://www.myweather2.com/developer/forecast.ashx?uac=29bsTnYaZT&output=json&query=50323&temp_unit=f','weatherfile.txt')

然后是打开该文件的命令

with open ('/home/pi/weatherfile.txt','r') as f:
    print(f.read())

这是我得到的输出

{ "weather": { "curren_weather": [ {"humidity": "62", "pressure": "1007", "temp": "86", "temp_unit": "f", "weather_code": "1", "weather_text": "Partly cloudy",  "wind": [ {"dir": "S", "speed": "6", "wind_unit": "kph" } ] } ],  "forecast": [ {"date": "2013-06-26",  "day": [ {"weather_code": "0", "weather_text": "Sunny skies",  "wind": [ {"dir": "W", "dir_degree": "266", "speed": "11", "wind_unit": "kph" } ] } ], "day_max_temp": "93",  "night": [ {"weather_code": "0", "weather_text": "Clear skies",  "wind": [ {"dir": "NW", "dir_degree": "313", "speed": "22", "wind_unit": "kph" } ] } ], "night_min_temp": "68", "temp_unit": "f" }, {"date": "2013-06-27",  "day": [ {"weather_code": "1", "weather_text": "Partly cloudy skies",  "wind": [ {"dir": "NNE", "dir_degree": "27", "speed": "18", "wind_unit": "kph" } ] } ], "day_max_temp": "86",  "night": [ {"weather_code": "29", "weather_text": "Thundery outbreaks possible",  "wind": [ {"dir": "NNE", "dir_degree": "20", "speed": "18", "wind_unit": "kph" } ] } ], "night_min_temp": "65", "temp_unit": "f" } ] }}

我希望它输出得更好一点,有什么办法可以做到这一点吗?

这是我尝试过的更新

froom urllib.request import urlretrieve
urlretrieve('http://api.wunderground.com/api/015098ae0bc15cce/conditions/q/IA/Urbandale.json','weatherfile.txt')
pp = pprint.PrettyPrinter(indent=4)
with open ('/home/pi/weatherfile.txt','r') as f:
    d = json.loads(f.read())
    pp.pprint(d)

我收到此错误

Traceback (most recent call last):
File "C:/Users/Grant/Desktop/getweather.py", line 3, in <module>
pp = pprint.PrettyPrinter(indent=4)
NameError: name 'pprint' is not defined  

最佳答案

我假设它是 JSON 数据,因此您可以使用 json 漂亮地打印它:

import json
with open ('/home/pi/weatherfile.txt','r') as f:
    d = json.loads(f.read())
    json.dumps(sort_keys=True, indent=4, separators=(',', ': '))

或者你可以使用pprint来做到这一点:

import json
import pprint
pp = pprint.PrettyPrinter(indent=4)
with open ('/home/pi/weatherfile.txt','r') as f:
    d = json.loads(f.read())
    pp.pprint(d)

关于python - 在Python中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17309766/

相关文章:

python - 根据标签的多数计数过滤数据框中的重叠行

java - 尝试显示我的应用的天气图标时遇到问题

sql - 如何使用 BigQuery 获取任何城市的历史天气?

c++ - 随机但可预测的数字生成器? [C++]

python - 获取 n 的所有约数的该算法的运行时间复杂度是多少?

python - 将装饰器类应用于类方法

image - 我在哪里可以找到免费的天气图标?

javascript - 在 Javascript for 循环中调用 HTML 类很困难

python - 径向基函数库

python - 将具有常量参数的函数应用于 Pandas 数据框