기계는 거짓말하지 않는다

Python 객체 파일로 저장, 직렬화 (pickle) 본문

Python

Python 객체 파일로 저장, 직렬화 (pickle)

KillinTime 2023. 1. 28. 17:10

Python 객체를 파일로 저장할 때 기본 내장된 pickle 모듈을 사용할 수 있다.

Python pickle module docs

 

pickle — Python object serialization

Source code: Lib/pickle.py The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is...

docs.python.org

간단한 사용법은 아래와 같다.

import pickle

class TempClass(object):
    def __init__(self, string: str, val: int):
        self.string = string
        self.val = val

with open('temp_data.pkl', 'wb') as wf: # pickle.HIGHEST_PROTOCOL 대용량 메모리 인수
    temp1 = TempClass('temp1', 100)
    pickle.dump(temp1, wf, pickle.HIGHEST_PROTOCOL)

    temp2 = TempClass('temp2', 200)
    pickle.dump(temp2, wf, pickle.HIGHEST_PROTOCOL)


with open('temp_data.pkl', 'rb') as rf:
    temp1 = pickle.load(rf)
    print(temp1.string)
    print(temp1.val)

    temp2 = pickle.load(rf)
    print(temp2.string)
    print(temp2.val)

Comments