import chardet path='test.txt' bytes = min(100, os.path.getsize(path))
raw = open(path, 'rb').read(bytes)
result = chardet.detect(raw)
encoding = result['encoding'] with open(path, 'r+', encoding=encoding, errors='ignore') as f_in:
...
bytes = min(100, os.path.getsize(path))
raw = open(path, 'rb').read(bytes)
取文件中的一部分字节,进行判断文件所用编码方式。可适当调整100这个值的大小以提高判断的准确性。