Write and read back data - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Write and read back data (/thread-36962.html) |
Write and read back data - Aggie64 - Apr-17-2022 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. RE: Write and read back data - Axel_Erfurt - Apr-17-2022 https://www.w3schools.com/python/ref_func_open.asp "r" - Read "a" - Append "w" - Write RE: Write and read back data - bowlofred - Apr-17-2022 (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() RE: Write and read back data - Aggie64 - Apr-18-2022 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 RE: Write and read back data - Aggie64 - Apr-18-2022 (Apr-18-2022, 12:59 PM)Aggie64 Wrote: Your code worked!!! Many thanks. RE: Write and read back data - Aggie64 - Apr-18-2022 I meant to say I don't understand the difference in f.read(content) vs content=f.read(). RE: Write and read back data - bowlofred - Apr-18-2022 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. |