python-small-examples

@author jackzhenguo
@desc 获取文件编码
@tag
@version 
@date 2020/04/07
import chardet
from chardet import UniversalDetector

def get_encoding(file):
    with open(file, "rb") as f:
        cs = chardet.detect(f.read())
        return cs['encoding']
    
    detector = UniversalDetector()
    with open(file, "rb") as f:
        for line in f.readlines():
            detector.feed(line)
            if detector.done:
                break
        detector.close()
    return detector.result
[上一个例子](/python-small-examples/md/199.html) [下一个例子](/python-small-examples/md/201.html)