본문 바로가기

Python_Beginer/Study

Python Pickling / Unpickling

반응형

1. Python Pickle

파이썬 객체(파일)을 파일에 저장 하는 과정

리스트나 클랙스 같은 텍스트가 아닌 자료형을 파일로 저장하기 위하여 사용


1-1. Pickle 모듈 임포트

import pickle


1-2. Pickle 모듈 기본 사용법

with open('파일명', '파일모드') as file:
pickle.dump(데이터 변수, file)

Pickle의 파일모드는 바이트형식으로 작성하므로 wb를 사용한다. 여기서 b는 바이너리를 의미한다.


보통 확장자는 bin / dmp를 사용한다. 물론 다른 확장자를 사용해도 무관하다.


1-3. Pickle 예제 파일>

import pickle

dir = 'c:/windows/dir_pro'
ver = '2.0'
file_load = 'c:/program/en/en.exe'
user = {'ankiwoong':1.0, 'anjia':2.0}

with open('dir.bin', 'wb') as file:
pickle.dump(dir, file)
pickle.dump(ver, file)
pickle.dump(file_load, file)
pickle.dump(user, file)


1-4. 예제 파일 출력물

dir.bin



2. Python Unpickling

Pickling으로 작업 한 파일을 불러들여 출력하는 과정

Unpickling 또한 Pickling 모듈을 사용한다.

Unpickling에 주의사항은 pickling한 갯수만큼 순서대로 unpickling(pickle.load) 해야된다.


2-1. Pickling 모듈 임포트

import pickle


2-2. Unpiling 모듈 기본 사용법

with open('파일명', '파일모드') as file:
p1 = pickle.load(file)

Unpickle의 파일모드는 바이트형식으로 읽어들이므로 rb를 사용한다. 여기서 b는 바이너리를 의미한다.



2-3. unpiling 예제 파일

import pickle

with open('dir.bin', 'rb') as file:
p1 = pickle.load(file)
p2 = pickle.load(file)
p3 = pickle.load(file)
p4 = pickle.load(file)
print(p1)
print(p2)
print(p3)
print(p4)


2-4. 예제 파일 출력물

c:/windows/dir_pro

2.0

c:/program/en/en.exe

{'ankiwoong': 1.0, 'anjia': 2.0}


Process finished with exit code 0

반응형

'Python_Beginer > Study' 카테고리의 다른 글

Python Variable Arguments(가변 길이 함수) - args  (0) 2019.05.11
Python String(문자열)  (0) 2019.04.28
Python Open - writelines / readlines / readline  (0) 2019.04.25
Python Open - With as  (0) 2019.04.25
Python Open - w / r / a  (0) 2019.04.25