问题
python直接打开非utf-8编码格式的文件,并使用readline()读取内容,会出现字节解析失败。
with open(file, 'r') as f:
str = f.readline()
报错信息如下:
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start byte
解决办法
使用chardet库可以分析字节流的编码格式。
方法一:
import chardet
def predict_encoding(file_path):
with open(file_path, 'rb') as f:
d = chardet.detect(f.read())
print(d)
file_encoding = d['encoding']
return file_encoding
方法一会将文件中所有内容进行编码解析,遇到文件内容较大时,执行时间较长。
我们也可以只读取文件的开头一定行数的字节,再解析其编码,如方法二只读取文件的前1000行:
方法二:
import chardet
def predict_encoding(file_path, n_lines=1000):
with open(file_path, 'rb') as f:
rawdata = b''.join([f.readline() for _ in range(n_lines)])
d = chardet.detect(rawdata)
print(d)
file_encoding = d['encoding']
return file_encoding