如何在python中编写一个检查以查看文件是否有效UTF-8?

Jox*_*Jox 17 python utf-8

如标题中所述,我想检查给定的文件对象(打开为二进制流)是有效的UTF-8文件.

任何人?

谢谢

Dan*_*ach 23

def try_utf8(data):
    "Returns a Unicode object on success, or None on failure"
    try:
       return data.decode('utf-8')
    except UnicodeDecodeError:
       return None

data = f.read()
udata = try_utf8(data)
if udata is None:
    # Not UTF-8.  Do something else
else:
    # Handle unicode data
Run Code Online (Sandbox Code Playgroud)


mic*_*ael 9

你可以做点什么

import codecs
try:
    f = codecs.open(filename, encoding='utf-8', errors='strict')
    for line in f:
        pass
    print "Valid utf-8"
except UnicodeDecodeError:
    print "invalid utf-8"
Run Code Online (Sandbox Code Playgroud)