모든 경우에 해당하는지는 확인하지 못함.
내 경우는 파이썬 2.X 버전에서 pickle을 dump 하고 3.X 버전에서 load 한 경우 아래와 같은 에러가 발생
>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128)
근본적인 이유를 찾아보니 python2 버전과 3버전에서는 문자열을 다루는 방식이 다르다.
Python2 vs Python3 : string handling
- python2 : this string literal is called a "str" object but its stored as bytes. If you prefix it with "u" you get a "unicode" object which is stored as Unicode code points.
- python3 : this string literal is a "str" object that stores Unicode code points by default. You can prefix it with "b" to get a bytes object or use .encode.
즉, 2버전에서는 byte, 3버전에서는 unicode를 기본 데이터 타입으로 사용한다.
그렇다면 읽을때 바이트 타입으로 읽어주면 되겠지..
with open(filePath, 'rb') as f:
data = pickle.load(f, encoding='byte')
혹 pickle에 데이터를 딕셔너리로 저장 했을경우 읽을때 key 값 앞에도 'b'를 붙여줘서 byte로 읽자
sID = data[b"userID"]
sAddress = data[b"userAddress"]
...
위 방법이 안통해서 찾은 다른방법 (20.02.11. 추가)
with open(picklePath,'rb') as file: # Binary read
u = pickle._Unpickler(file)
u.encoding = 'latin1'
p = u.load()
'Programming > Python' 카테고리의 다른 글
pip에서 ImportError: cannot import name 'main' 를 해결하자 (0) | 2019.09.20 |
---|---|
imread, imwrite 에서 한글(유니코드)로 인한 문제를 해결하자 (3) | 2019.09.04 |
list 생성과 초기화 같이 하자 (0) | 2019.08.14 |
list 에서 최대값과 최대값의 index를 찾아보자 (0) | 2019.08.14 |
numpy의 array를 저장하고 읽어보자 (0) | 2019.08.08 |