0

Say I ran some code that produces multiple arrays as its output. How might I save the entire output in one go as in matlab?

In matlab I'd simply say save(data) -> load('data').

Apologies if this is a basic quesiton.

Dimitri_896
  • 137
  • 4
  • Does this answer your question? https://stackoverflow.com/questions/2960864/how-to-save-all-the-variables-in-the-current-python-session – Jussi Nurminen Oct 12 '21 at 08:36
  • Does this answer your question? [How to save and load numpy.array() data properly?](https://stackoverflow.com/questions/28439701/how-to-save-and-load-numpy-array-data-properly) – Michael Szczesny Oct 12 '21 at 08:37

1 Answers1

0

How to save a python object:

To save objects to file in Python, you can use pickle:

  • Import the pickle module.
  • Get a file handle in write mode that points to a file path.
  • Use pickle.dump to write the object that we want to save to file via that file handle.

How to use it:

   import pickle 
   object = Object() 
   filehandler = open(filename, 'w') 
   pickle.dump(object, filehandler)

How to load a python object:

  • Import the pickle module.
  • Get a file handle in read mode that points to a file path that has a file that contains the serialized form of a Python object.
  • Use pickle.load to read the object from the file that contains the serialized form of a Python object via the file handle.

How to use it:

   import pickle 
   filehandler = open(filename, 'r') 
   object = pickle.load(filehandler)

Extras : save multiple objects at once

Obviously, using a list you can also store multiple objects at once:

object_a = "foo"
object_b = "bar"
object_c = "baz"

objects_list = [object_a , object_b , object_c ]
file_name = "my_objects.pkl"
open_file = open(file_name, "wb")
pickle.dump(objects_list, open_file)
open_file.close()
BlackMath
  • 1,708
  • 1
  • 11
  • 14