Home > Software engineering >  Is there a Python analog to matlab's "save()" function?
Is there a Python analog to matlab's "save()" function?

Time:10-13

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.

CodePudding user response:

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()
  • Related