binary 데이터 입출력
binary data -> 텍스트 인코딩을 하지 않고 입출력하는 데이터.
각 타입의 값들을 출력(binary) 할 때 "bytes" 타입으로 변환해서 출력
binary data를 입력받으면 'bytes' 타입으로 반환
각 타입 -> bytes : 출력
bytes -> 각 타입 : 입력
i = 10
with open("files/data.txt", 'wt') as fw: # 텍스트 쓰기 모드
fw.write(str(i))
with open("files/data.txt", 'rt') as fr: # 텍스트 읽기 모드
a = fr.read()
print(int(a) + 20)
i = 10
# binary data 로 출/입력
# 정수 i를 bytes 타입으로 변환
# (1, byteorder = "little", signed = True) -> (크기, 구성방식, 부호있는지 여부)
# byteorder - little : 유효숫자이외의 0을 앞에 채움 (00000001)
# big : 유효숫자 이외의 0을 뒤에 채움 (10000000)
# 정수 -> bytes, bytes -> 정수 ---> byteorder를 동일하게 지정
i_bytes = i.to_bytes(1, byteorder = "little", signed = True) # A.to_byte() -> A를 bytes형태로 타입을 바꾸겠다.
with open("files/data2.dat", "wb") as fo:
print(type(fo))
fo.write(i_bytes)
with open("files/data2.dat", "rb") as fi:
print(type(fi))
value = fi.read() # b 모드로 읽기 : bytes 타입으로 return
type(value) # bytes 형태로 바뀐것을 확인할 수 있다.
# bytes -> int 변환
i_value = int.from_bytes(value, byteorder = "little", signed = True) # int.from_bytes(value, ....) -> value를 int 형태로 다시 바꾼다
print(i_value + 50) # int 형태로 바뀌었기 때문에 연산이 가능하다.
지금까지의 코드 실행 과정은 아래와 같다.
출력 : int(원래타입) - 변환 -> bytes --출력--> 저장 --입력--> bytes -변환-> int(원래타입)
pickle 모듈을 이용한 객체 직렬화
객체 직렬화(Object Serialization)
- 객체의 속성값들을 bytes로 변환해 출력하는 것을 객체 직렬화(Object Serialization) 이라고 한다.
- bytes로 출력된 데이터를 읽어 객체화 하는 것을 객체 역직렬화(Object Deserialization) 이라고 한다.
pickle
- 객체 파일 입출력을 위한 파이썬 모듈
- mode : binary mode ("wb" 또는 "rb")
- 파일 확장자 : pkl 또는 pickle
fw = open("data.pkl", "wb") # 객체를 pickle에 저장하기 위한 output stream 생성
fr = open("data.pkl", "rb") # 파일에 저장된 객체를 읽어오기 위한 input stream 생성
메소드
- dump(저장할 객체, fw) : 출력
- load(fr): 입력 - 읽은 객체를 반환한다.
i = 10
import pickle
# 출력 -> 직렬화
with open('files/int_data.pickle', 'wb') as fo:
pickle.dump(i, fo)
# 입력 -> 역직렬화
with open("files/int_data.pickle", 'rb') as fi:
r_value = pickle.load(fi)
type(r_value), r_value # 결과 확인
l = [10, 'abc', True] # 다양한 타입의 리스트 생성
with open('files/list.pickle', 'wb') as fo: # binary 쓰기 모드
pickle.dump(l, fo) # 리스트l의 내용들을 출력한다.
with open('files/list.pickle', 'rb') as fi: # binary 읽기 모드
r_list = pickle.load(fi) # 변수 r_list에 읽은 객체를 저장
type(r_list), r_list # 결과 확인
from my_package import test_module as tm # my_package 디렉토리에 있는 test_module 모듈을 tm이라는 별칭으로 호출
p = tm.Person('홍길동', 30)
print(p)
f_name = 'files/person.pickle'
with open(f_name, 'wb') as fo:
pickle.dump(p, fo)
with open(f_name, 'rb') as fi:
r_person = pickle.load(fi)
print(type(r_person))
print(r_person)
'Data_Analysis_Track_33 > Python' 카테고리의 다른 글
| Python_09-2(Decorator) (0) | 2023.08.28 |
|---|---|
| Python_09(Iterable) (0) | 2023.08.25 |
| Python_08(입출력) (0) | 2023.08.24 |
| Python_07-2(Exception 발생시키기) (0) | 2023.08.24 |
| Python_07(예외처리) (0) | 2023.08.23 |