IT在线课程程序员IT@程序员猿媛

csv 文件编码格式的判断

2019-04-12  本文已影响63人  torrent_lsl

1. 现状

file = request.files["file"].read()

2. 可能接收的格式?

3. 解决现状

def string_encoding(data: bytes):
    """
    获取字符编码类型
    :param data: 字节数据
    :return:
    """
    UTF_8_BOM = b'\xef\xbb\xbf'
    CODES = ['UTF-8', 'GB18030', 'BIG5']
    # 遍历编码类型
    for code in CODES:
        try:
            data.decode(encoding=code)
            if 'UTF-8' == code and data.startswith(UTF_8_BOM):
                return 'UTF-8-SIG'
            return code
        except UnicodeDecodeError:
            continue
    return 'unknown'


file = request.files["test"].read()
format = string_encoding(file)
# 通过返回的编码格式做不同处理
if format == "GB18030":
    file = file.decode("gbk")
elif format == "UTF-8-SIG":
    file = file.decode("utf-8")
GB18030 编码文件字节内容
b'\xd3\xce\xcf\xb7\xc3\xfb\xb3\xc6,\xb9\xe3\xb8\xe6\xc3\xfb\xb3\xc6,\xca\xb1\xbc\xe4,\xbc\xc6\xb7\xd1\xb7\xbd\xca\xbd,\xb7\xb5\xc7\xb0\xcf\xfb\xba\xc4\r\n\xcd\xf2\xb9\xfa\xbe\xf5\xd0\xd1,RoC_And_T1_FR,2018-10-12,\xbc\xa4\xbb\xee,1000'

UTF-8-SIG 编码文件字节内容
b'\xef\xbb\xbf\xe6\xb8\xb8\xe6\x88\x8f\xe5\x90\x8d\xe7\xa7\xb0,\xe5\xb9\xbf\xe5\x91\x8a\xe5\x90\x8d\xe7\xa7\xb0,\xe6\x97\xb6\xe9\x97\xb4,\xe8\xae\xa1\xe8\xb4\xb9\xe6\x96\xb9\xe5\xbc\x8f,\xe8\xbf\x94\xe5\x89\x8d\xe6\xb6\x88\xe8\x80\x97\r\n\xe4\xb8\x87\xe5\x9b\xbd\xe8\xa7\x89\xe9\x86\x92,RoC_And_T1_FR,2018-10-12,\xe6\xbf\x80\xe6\xb4\xbb,1000'

上一篇 下一篇

猜你喜欢

热点阅读