How to write a check in python to see if file is v

2019-04-18 19:09发布

As stated in title, I would like to check in given file object (opened as binary stream) is valid UTF-8 file.

Anyone?

Thanks

标签: python utf-8
2条回答
你好瞎i
2楼-- · 2019-04-18 19:59
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
查看更多
倾城 Initia
3楼-- · 2019-04-18 20:03

You could do something like

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"
查看更多
登录 后发表回答