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