【问题标题】:write and read Dictionary Python 3写和读字典 Python 3
【发布时间】:2014-01-31 04:44:25
【问题描述】:

我想将天气信息写入一个文件并用另一个脚本读取它。目前我一直在写文件。 原代码:

#!/usr/bin/env python3
from pprint import pprint
import pywapi
import pprint
pp = pprint.PrettyPrinter(indent=4)

steyregg = pywapi.get_weather_from_weather_com('AUXX0022')


pp.pprint(steyregg)

这给了我这样的输出:

> {   'current_conditions': {   'barometer': {   'direction': u'falling
> rapidly',
>                                                'reading': u'1021.33'},
>                               'dewpoint': u'0',
>                               'feels_like': u'2',
>                               'humidity': u'67',
>                               'icon': u'32',
>                               'text': u'W'}},.......

所以我尝试了

#!/usr/bin/env python3
from pprint import pprint
import pywapi
import pprint
pp = pprint.PrettyPrinter(indent=4)

steyregg = pywapi.get_weather_from_weather_com('AUXX0022')

with open('weather.txt', 'wt') as out:
    pp.pprint(steyregg, stream=out)

但这会导致错误:

pprint() got an unexpected keyword argument 'stream'

我做错了什么?一旦它在另一个python脚本中工作,我如何阅读wheater.txt?还是有更优雅的方式来捕获这样的数据并在其他地方使用它?

提前致谢

【问题讨论】:

    标签: python json dictionary weather


    【解决方案1】:

    PrettyPrinter 类的pprint 方法 不接受stream 关键字参数。在此行中创建对象时提供流:

    pp = pprint.PrettyPrinter(indent=4)
    

    或使用函数pprint.pprint,它接受stream 关键字参数。

    这就是错误的原因。一个更基本的问题是:为什么要使用pprint 模块,而问题的标题是“write and read xml Python 3”? pprint 模块不生成 XML。有关使用 python 处理 XML 的一些想法,请参阅https://wiki.python.org/moin/PythonXml

    还要注意pywapi.get_weather_from_weather_com 返回一个python 字典。该函数已将 XML 数据转换为字典,因此您无需读取任何 XML。请参阅此example(如果您还没有的话)。

    您可以将字典保存为 JSON 文件。

    import json
    
    with open('weather.txt', 'wt') as out:
        json.dump(steyregg, out, indent=4)
    

    【讨论】:

    • 我不需要 xml,我认为这会做到这一点,我只想保存天气信息并在另一个脚本中可用。只是在寻找一种方法来做到这一点。
    • 好的。我会谷歌如何处理字典。看一下json
    • 我在答案中添加了关于 JSON 的注释。
    猜你喜欢
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 2018-03-19
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多