-1

In my Python project, I'm using an object class Forecast with some attributes (temperature, humidity etc...). I want to use 2 scripts, one for writing the data into a binary file, one to read it.

I tried both f = open(file,"wb")

f.write(object)

and

pickle.dump(object, open(file,"wb"))

but my problem is writing class objects with pickle won't let me read it properly with pickle.load, and f.write won't let me do this because 'bytes-like objects are required'.

Can someone tell me if there is any other way to do it?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

-1
import pickle
with open('file','wb')as f:
         pickle.dump(object,f)
#the above argument is used to create a file using write byte 'wb'
with open('file','rb')as f:
         mp=pickle.load(f)
#the above argument is used to load the previous saved model into object 'mp'

Do let me know if that helps ;)

  • so basically mp will store in one variable all the date file keeps? – Shortcircuit Aug 09 '20 at 19:02
  • Shortcircuit: Yes, that's how it works. – martineau Aug 09 '20 at 19:07
  • ok, so the thing is I want to do an IoT project Arduino based, kinda weather station with the forecast. the data received from sensors will be sent to a CPU that will compute later the data in order to show other things (heat index etc), this is easy to do at different timestamps this data is read, computed, after that I want to write the object Forecast in a bin file and to store it there for a later ML so the correct question would be: "I want to write an object in a file, but when I read it, I will read a vector of that kind of objects" idk how clearly it is explained... – Shortcircuit Aug 09 '20 at 19:11
  • Tushar Sharma: I tried your code, it works but it will only take the first object stored in the file, I cannot access the 2nd one – Shortcircuit Aug 09 '20 at 19:32