[module] pickle

반디·2023년 3월 7일
0

Python

목록 보기
7/11

object serialization(직렬화)을 지원하는 pickle 모듈에 대해 알아봅니다.

복잡한 구조의 object들을 넘겨주거나 object의 internal state를 저장해야할 때가 있습니다. 이를 serialization을 통해 수행할 수 있습니다.

  • Serialization: 시스템 내부의 object state 또는 data structure를 외부 시스템에서도 사용할 수 있는 형태(file, memory buffer 등)로 byte 형태로 변환하는 것

pickle

파이썬 object structure의 serialization 또는 de-serialization을 지원

  • pickling: 파이썬 object hierarchy \rightarrow byte stream (binary file or bytes-like object)
  • unpickling: byte stream \rightarrow 파이썬 object hierarchy
Example
  1. pickle 파일 생성 후 값 쓰기
import pickle

test_dict = {"dog": "puppy"}

#method 1
with open("test.pickle", "wb") as outfile: #test.pickle 파일에 test_dict 값을 write 
    pickle.dump(test_dict, outfile)

#method 2
f = open("test.pickle", "wb")
pickle.dump(test_dict, f)
f.close()
  1. pickle 파일의 값 읽어오기
import pickle

#method 1
with open("test.pickle", "rb") as infile:
   reconstructed_data = pickle.load(infile)

#method 2
f = open("test.pickle", "rb")
reconstructed_data = pickle.load(f)
f.close()
  1. object serialization
import pickle
 
class CustomClass:
    def __init__(self, data):
        print(data)
        self.data = data
 
# Create an object of CustomClass
test_dict = {"dog": "puppy"}
new_class = CustomClass(test_dict)
 
# Serialize and deserialize
pickled_data = pickle.dumps(new_class)
reconstructed = pickle.loads(pickled_data)
 
# Verify
print("Data from reconstructed object:", reconstructed.data)

참고문헌

profile
꾸준히!

0개의 댓글