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

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

上一篇:html+css+js实现标签页切换


下一篇:图解SQL inner join、left join、right join、full outer join、union、union all的区别