bytes
타입으로 변환해서 출력bytes
타입으로 반환
# int -> str 변환해 출력
i = 10
with open ("files/data.txt, "wt") as fw:
fw.write(str(i)) # text mode로 출력 -> str타입만 가능
# str -> int(원래타입)으로 변환해 읽어오기
with open("files/data.txt","rt" as fr :
a = fr.read() #text 모드 : return type = str
print(int(a) + 20 )
>>> 30
-to_bytes()
: write()에 binary data를 bytes
타입으로 반환해 입력
- '타입 변환 코드' (입/출력한 데이터의 타입을 자동으로 변환하는 코드)
- to_bytes(크기(length), 구성방식(bytes order), [부호있는지 여부])
1. length(크기) - (int)변환된 바이트 열의 길이
2. bytesorder - little : 유효숫자 이외의 0을 앞에 채움(0000001)
big : 유효숫자 이외의 0 을 뒤에 채움(1000000)
정수 -> bytes, bytes -정수 ==> bytesorder를 동일하게 지정
3. 부호비트 - 양수 0, 음수 1, signed = True : 부호비트 존재
i = 10
# 1) binary data로 출력
# 정수 i를 bytes타입으로 변환
##write()에 작성하는 값을 bytes type으로 변환해야한다.
i_bytes = i.to_bytes(1, byteorder = "little", signed = True)
#파일 읽기 - 출력 - 파일닫기
with open("files/data2.txt","wb") as fo: # b모드로 쓰기
fo.write(i_bytes)
from_bytes
: read() 된 bytes타입 data를 원래 binary type으로 반환해 읽어냄#파일 읽기 - 출력 - 파일닫기 : bytes타입으로 읽기
with open("files.data2.dat","rb") as fo:
value = fi.read()
# bytes타입 -> 원래 타입으로 변환
i_value = int.from_bytes(value, bytesorder = "little", signed = True)
print(i_value +50)
>>> 60
# w,wt,wb
fo.write(str) # wt
fo.write(bytes) #wb
# r, rt, rb
fi.read() : str #rt
fi.read() : bytes #rb
bianary 데이터의 type에 따라서 입출력할 때마다 데이터를 bytes로 변환하는 과정을 자동화한 것이pickle 모듈
(객체 파일 입출력을 위한 파이썬 모듈)
데이터 입출력시 (import pickle 를 한 후)
1) 경로의 파일확장자를 pkl
,pickle
로 설정하고
2) open(): mode => binary mode로 설정하면 자동으로 알맞은 type으로 객체의 값(데이터)를 인식하고 bytes로 변환한다.
3) 출력 메소드는 bump, 입력 메소드는 load를 사용한다.
stream 생성
ex.
fw = open("data.pkl", "wb") # output stream 생성(객체를 pickle에 저장)
fr = open("data.pkl", "rb") # input stream 생성(저장된 객체를 읽어옴)
메소드 (단 2개!)
- pickle. bump , pickle.load
dump(저장할 객체, fw(output stream))
: 출력 - 객체의 속성값들을 bytes로 변환(객체 직렬화) load(fr(input stream))
: 입력 - bytes로 출력된 데이터를 원래 객체로 반환(객체 역직렬화) #1. int
i = 10
import pickle
# 출력 -> 직렬화
with open("files/int_data.pickle" ,"wb") as fo:
pickle.dump(i,fo #output stream) # dump(저장할 객체, output stream)
# 입력 -> 역직렬화 : 원래 파일로 읽어들이는 것
with open("files/int_data.pkl", "rb") as fi:
r_value = pickle.load(fi)
type(r_value), r_value
>>>int(int, 10)
#2. list type
l = [10,"abc", True]
with open("files/list.pickle", "wb") as fo :
pickle.dump(l, fo)
with open("files/list.pickle", "rb") as fi :
r_list = pickle.load(fi)
type(r_list), r_list
>>> (list, [10, 'abc', True])
#3 .class type
from my_package import test_module as tm
p = tm.Person("홍길동", 20)
print(p)
>>> 이름 : 홍길동, 나이: 20
# 출력 -> 직렬화
with open("files/person.pickle", "wb") as fo:
pickle.dump(p, fo)
# 입력 -> 역직렬화
with open(f_name, "rb") as fi:
r_person = pickle.load(fi)
type(r_person)
>>> my_packge.test_module.Person #person class의 한 instance임을 알려줌
print(r_person)
>>> 이름 : 홍길동, 나이: 20