def try_utf8(data):
    """Returns a Unicode object on success, or None on failure"""
try:
    return data.decode('utf-8')
except UnicodeDecodeError:
    pass
How to write a check in python to see if file is valid UTF-8?