Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - convert binary data to utf-8

Tags:

python

utf-8

_f = open("c:/go-next.png", "rb")
data = _f.read()
_f.close()
data.encode("utf-8")

# Error: UnicodeDecodeError: file <maya console> line 1: ascii # 

As you see I open a image file, and the data is type. But I have to convert it to utf-8. Maybe binary data has some extra char (or not), it conflict with conversion. Is there any way to solve it?

like image 252
Hyun-geun Kim Avatar asked Dec 15 '22 14:12

Hyun-geun Kim


2 Answers

You can always map a str to unicode using the latin-1 codec. Once you have a unicode, you can always encode it in utf-8:

data.decode('latin-1').encode("utf-8")
like image 173
unutbu Avatar answered Dec 21 '22 11:12

unutbu


Text encodings only apply to text. Do not attempt to use them on binary data.

like image 32
Ignacio Vazquez-Abrams Avatar answered Dec 21 '22 10:12

Ignacio Vazquez-Abrams