python3 不知文件编码情况下打开文件代码记录

 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这个值的大小以提高判断的准确性。

posted @ 2017-06-27 16:53  丛影HHZ  阅读(367)  评论(0编辑  收藏  举报