Closed mindjun closed 5 years ago
open
conf_as_dict
chardet
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
这个功能可以
背景
open
方法时,需要指定编码格式,否则会出现乱码的情况conf_as_dict
读取文件配置时,也需要指定编码格式步骤
chardet
,获取文件编码举例