Question

I want to write weather information to a file and read it with another script. Currently I'm stuck at writing to file. Original Code:

#!/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)

this give me output like this:

> {   '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'}},.......

So I tried

#!/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)

But this leads to Error:

pprint() got an unexpected keyword argument 'stream'

What am I doing wrong? How can i read wheater.txt once it works in another python script? Or is there a more elegant way to capture Data like this and use it somewhere else?

Thanks in Advance

Was it helpful?

Solution

The pprint method of the PrettyPrinter class does not accept a stream keyword argument. Either give the stream when you create the object in this line:

pp = pprint.PrettyPrinter(indent=4)

or use the function pprint.pprint, which accepts a stream keyword argument.

That's the reason for the error. A more fundamental question is: why you are using the pprint module, when title of the question is "write and read xml Python 3"? The pprint module does not generate XML. See https://wiki.python.org/moin/PythonXml for some ideas on handling XML with python.

Also note that pywapi.get_weather_from_weather_com returns a python dictionary. The function has already converted the XML data into a dictionary, so you don't have to read any XML. See this example (if you haven't already).

You could save the dictionary as a JSON file.

import json

with open('weather.txt', 'wt') as out:
    json.dump(steyregg, out, indent=4)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top