chinapnr / fishbase

自主开发、整理的一套 Python 基础函数库,涵盖 system 系统增强包、logger 日志记录增强包、file 文件处理增强包、 date 日期处理函数包、data 数据信息处理函数包、csv 处理增强函数包、crypt 加密/编码增强包等,可减少程序开发工作量、降低引用复杂度。
MIT License
94 stars 29 forks source link

fish_file, get_file_encoding 获取文件编码 #226

Closed mindjun closed 5 years ago

mindjun commented 5 years ago

背景

步骤

举例

def get_file_encoding(file):
    # 判断给定路径是否是一个文件
    flag = pathlib.Path.is_file(file)
    if not flag:
        raise RuntimeError('file {}, does not exist'.format(file))

    # 读入文件
    with open(file, 'rb') as f:
        buf = f.read()
        # 获取文件信息
        file_info = chardet.detect(buf)

        encoding = file_info['encoding']
        if encoding.startswith(('utf-8', 'UTF-8')):
            result_encoding = encoding
        else:
            result_encoding = 'GB2312'
        return result_encoding
itaa commented 5 years ago

这个功能可以