[Python] Saving and Restoring Running Objects to a File: How to Use pickle

If you want to save (serialize) complex data generated by a Python program, such as class instances, lists, or dictionaries, exactly as they are to a file and restore (deserialize) them later, use the standard library pickle module.

Unlike JSON format, pickle can save custom class instances while maintaining their type information. Therefore, it is widely used for temporarily backing up data or saving machine learning models.

目次

Implementation Example: Managing RPG Save Data

In this example, we will create an object holding game character information (name, job, level) and implement a “Save & Load” feature to store and restore it as a binary file.

Source Code

import pickle

# 1. Define the data structure (class) to save
class GameCharacter:
    def __init__(self, name, job, level):
        self.name = name
        self.job = job
        self.level = level

    def __str__(self):
        return f"[{self.job}] {self.name} (Lv.{self.level})"

    def level_up(self):
        self.level += 1
        print(f">> {self.name} has leveled up!")

# --- Main Process ---

# 2. Create an instance (Data in memory)
hero = GameCharacter("Arthur", "Hero", 45)

print("--- Current Status (Before Save) ---")
print(hero)

# 3. Save data to a file (Serialize)
# Since pickle uses binary format, you must open the file in 'wb' (Write Binary) mode
save_file = "adventure_log.pkl"

with open(save_file, "wb") as f:
    # pickle.dump(object_to_save, file_object)
    pickle.dump(hero, f)
    print(f"\n>> Recorded in adventure log '{save_file}'.")

print("-" * 30)

# 4. Load data from the file (Deserialize)
# 'rb' (Read Binary) mode is also mandatory for loading
with open(save_file, "rb") as f:
    # pickle.load(file_object) restores the original object
    loaded_hero = pickle.load(f)

print("--- Restored Data (After Load) ---")
print(loaded_hero)

# Verify if the restored object retains its original functions (methods)
loaded_hero.level_up()
print(f"Status after update: {loaded_hero}")

Execution Result

--- Current Status (Before Save) ---
[Hero] Arthur (Lv.45)

>> Recorded in adventure log 'adventure_log.pkl'.
------------------------------
--- Restored Data (After Load) ---
[Hero] Arthur (Lv.45)
>> Arthur has leveled up!
Status after update: [Hero] Arthur (Lv.46)

Explanation

How pickle Works

  • Serialize (dump): Converting Python objects (data in memory) into a “byte stream” that can be saved or transferred.
  • Deserialize (load): Reconstructing the original Python object from the byte stream.

Important Notes

  • Binary Mode (wb, rb): The data handled by pickle is binary, not text. Always specify the b flag when using the open() function.
  • Security Risk: pickle.load() can execute arbitrary code if it loads a file created with malicious intent. Never load pickle files received from untrusted sources.
  • Difference from JSON:
    • JSON: Text format. Highly compatible with other languages, but limited in the types it can save (custom classes need conversion).
    • Pickle: Binary format. Python-specific, but can save almost any Python object as is.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次