【问题标题】:How to write a check in python to see if file is valid UTF-8?如何在 python 中编写检查以查看文件是否为有效的 UTF-8?
【发布时间】:2011-03-17 04:56:42
【问题描述】:

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

有人吗?

谢谢

【问题讨论】:

    标签: python utf-8


    【解决方案1】:

    你可以这样做

    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"
    

    【讨论】:

    • 只使用一行会更简单:codecs.open("path/to/file", encoding="utf-8", errors="strict").readlines() 而不是 3。
    【解决方案2】:
    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
    

    【讨论】:

    • 很明显,当有更多这样简单的解决方案时,我的功课做得不够好:(谢谢!
    猜你喜欢
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 2023-01-13
    • 2013-08-16
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多