Python save all objects

How to save and load objects to and from file in Python via facilities from the pickle module

There are times when it is more convenient for us to choose object serialization over database management systems for the persistency of the data that our Python scripts work with.

In this post, I document how we can save and load objects to and from file in Python using facilities from the pickle module.

Saving objects to file in Python

To save objects to file in Python, we typically go through the following steps:

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

With these steps in mind, let’s us create a Python script, save_dictionary_to_file.py , with the following Python codes:

# Step 1 import pickle config_dictionary = # Step 2 with open('config.dictionary', 'wb') as config_dictionary_file: # Step 3 pickle.dump(config_dictionary, config_dictionary_file)

In step 1, we import the pickle module with the import keyword.

In step 2, we use the with keyword and the open function to create a file handle that points to config.dictionary in the same directory where we will run save_dictionary_to_file.py .

The first string that we supply to the open function denotes the filepath to write our dictionary of values. The second string that we supply to the open function indicates that we want a file handle that writes binary contents to the file.

Читайте также:  Управление контента на html

The with keyword ensures that the file handle generated by the open function is closed after our dictionary is serialized to file.

Finally in step 3, we use the pickle.dump function to write the contents of our dictionary to a file that will be named as config.dictionary .

After running save_dictionary_to_file.py , we should be able to see the config.dictionary file in the same directory where we run our Python script.

Loading objects from file in Python

To load the object from file in Python, we typically go through the following steps:

  1. Import the pickle module.
  2. 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.
  3. Use pickle.load to read the object from the file that contains the serialized form of a Python object via the file handle.

With these steps in mind, let us create a Python script, load_dictionary_from_file.py with the following Python codes:

# Step 1 import pickle # Step 2 with open('config.dictionary', 'rb') as config_dictionary_file: # Step 3 config_dictionary = pickle.load(config_dictionary_file) # After config_dictionary is read from file print(config_dictionary)

Similar to writing the dictionary to file, we import the pickle module in step 1.

In step 2, we use the with keyword with the open function to get a file handle that points to config.dictionary in the same directory where we will run load_dictionary_from_file.py .

As with saving the dictionary to file, we supply config.dictionary as the first input to the open function to indicate the file path to the file which contains the serialized dictionary. This time round, we supply the string ‘rb’ instead of ‘wb’ to indicate that we want a file handle that reads binary contents from the file.

Читайте также:  Php функция удаления из файла

Finally in step 3, we load the dictionary from the file to the config_dictionary variable via the pickle.load function.

Once we had loaded the dictionary from the file to the config_dictionary variable, we use the print function to print the dictionary contents to the standard output.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.

Источник

How to Use Pickle to Save Objects in Python

Two rows of pickles

Albert Lukaszewski, Ph.D., is a veteran computer programmer, software engineer, and author, who specializes in the Python language.

Pickle, which is part of the Python library by default, is an important module whenever you need persistence between user sessions. As a module, pickle provides for the saving of Python objects between processes.

Whether you are programming for a database, game, forum, or some other application that must save information between sessions, pickle is useful for saving identifiers and settings. The pickle module can store things such as data types such as booleans, strings, and byte arrays, lists, dictionaries, functions, and more.

Note: The concept of pickling is also known as serialization, marshaling, and flattening. However, the point is always the same—to save an object to a file for later retrieval. Pickling accomplishes this by writing the object as one long stream of bytes.

Pickle Example Code in Python

To write an object to a file, you use a code in the following syntax:

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

Here’s how a real-world example looks:

import pickle 
import math
object_pi = math.pi
file_pi = open('filename_pi.obj', 'w')
pickle.dump(object_pi, file_pi)

This snippet writes the contents of object_pi to the file handler file_pi, which in turn is bound to the file filename_pi.obj in the directory of execution.

Читайте также:  Html div border with text

To restore the value of the object to memory, load the object from the file. Assuming that pickle has not yet been imported for use, start by importing it:

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

The following code restores the value of pi:

import pickle 
file_pi2 = open('filename_pi.obj', 'r')
object_pi2 = pickle.load(file_pi2)

The object is then ready for use once again, this time as object_pi2. You can, of course, reuse the original names, if you prefer. This example uses distinct names for clarity.

Things to Remember About Pickle

Keep these things in mind when using the pickle module:

  • The pickle protocol is specific to Python – it’s not guaranteed to be cross-language compatible. You most likely cannot transfer the information to make it useful in Perl, PHP, Java, or other languages.
  • There is also no guarantee of compatibility between different versions of Python. IThe incompatibility exists because not every Python data structure can be serialized by the module.
  • By default, the latest version of the pickle protocol is used. It remains that way unless you manually change it.

Tip: Also find out how to use shelve to save objects in Python for another method of maintaining object continuity.

Источник

Оцените статью