最近作一个项目,须要读取文件内容,可是文件的编码方式有可能都不同。有的使用GBK,有的使用UTF8。因此在不正确读取的时候会出现以下错误:django
UnicodeDecodeError: 'gbk' codec can't decode byte
并且当你使用rb模式读取文件时候,返回的结果经过django返回的json会出现下面错误:json
TypeError: b'\xbc\x8c\xe6\x9c\xaa\xe6\x9d\xa5' is not JSON serializable
总之就是编码不对,因此要先能识别文件的编码方式,而后根据此编码方式进行对文件编码,最后返回文件内容。编码
解决方法以下:code
with open("your_file", 'rb') as fp: file_data = fp.read() result = chardet.detect(file_data) file_content = file_data.decode(encoding=result['encoding'])
注: chardet是第一个第三方库,你须要本身使用pip进行安装。ip
@完it