最近在学习Flask
框架,网上看着Flask 课程,一边动手操作,但是可能Python的版本不同,我在实验的过程中总是有不少的问题。
系统:win10
Python版本:python3.5.2
Pycharm: 4.07
错误信息:
UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa7 in position 4: illegal multibyte sequence
python的这类编码错误大致有两种:UnicodeDecodeError和UnicodeEncodeError
其实明白了处理的字符串类型和要处理成编码还是解码的方式就容易多了。
解决方法可以在打开文件的时候加入rb
参数;
with open(filename,'rt') as md_file:
因为默认open的参数为’r’,如果使用’rb’二进制模式,对于计算机来说不存在编码问题。
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
返回数据时只需加上decode编码即可:
return content.decode('utf-8')
上面就是最简单的方法了;
另一个方法差不多,也是在open文件的时候加上编码:
with open(filename,encoding='utf-8') as md_file:
返回数据时需要把原编码和目标编码都加上:
return content.encode('utf-8').decode('utf-8')
另一例子,原本网页就是Utf-8的编码,但是在Python3下使用urllib库时获取的网页是字节码格式,所以就要加上decode解码成utf-8;
import sys
import urllib.request
def Main():
htmlresult = urllib.request.urlopen('http://www.58jb.com').read()
print(htmlresult.decode('utf-8'))
if __name__ == '__main__':
Main()
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码decode
成unicode,再从unicode编码encode
成另一种编码。
decode(‘gbk’) :解码,把gbk编码转换成unicode编码。
encode(‘gbk’) :编码,把unicode编码转换成其它的编码,这里转换成gbk。