Python Forum

Full Version: Write and read back data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a working Python 3 program that reads XML data from a URL and processes the data received
The code shown below is how the data is received
req= urllib.Request(url,headers=.....)
content = urllib.request.urlopen(req).read #req comes from a statement
root=ET.fromstring(content)
for metar in root.iter('METAR')
#the code in the for statement process the metar data

I want to be able to save the data in the variable "content" or "root" to a file and then later read the data back just as though I had received it from the URL and then process the data the same way as is done when read from a URL.

I tried the following:
with open("savedata",'r+',encoding='utf-8') as f:
f.write(content)
with open('savedata','r+',encoding='utf-8') as f:
f.read(content)
I get an error on the write that the data must be str, not bytes

I believe the data in the variable "content" is all ascii data.

an example of the data in the variable "content" starts out as follows:
<?xml version ="1.0 encoding ='UTF-8"?>\n<response xmlns:xsd="http...

Thanks, in advance for any help.
https://www.w3schools.com/python/ref_func_open.asp

"r" - Read

"a" - Append

"w" - Write
(Apr-17-2022, 09:01 PM)Aggie64 Wrote: [ -> ]I get an error on the write that the data must be str, not bytes

So it may be ascii (or utf-8) inside, but hasn't been decoded to that. In which case, you probably want to write and read it as binary.
with open("savedata", "wb") as f:
    f.write(content)

with open("savedata", "rb") as f:
    content = f.read()
Your code worked!!! Many thanks.

I don't understand the difference in f.write(content) vs content=f.read().
I need to do more reading.
Thanks again Smile
(Apr-18-2022, 12:59 PM)Aggie64 Wrote: [ -> ]Your code worked!!! Many thanks.

I don't understand the difference in f.write(content) vs content=f.read().
I need to do more reading.
Thanks again Smile
I meant to say I don't understand the difference in f.read(content) vs content=f.read().
The only argument that read() takes is an optional maximum size of characters to read. And it returns the data, so you'll want to assign it.