【问题标题】:Read first line of file without encoding读取文件的第一行而不进行编码
【发布时间】:2018-05-11 08:04:13
【问题描述】:

我想使用 Python 读取可以为不同用户(假设所有标准库编解码器或其他标准库编解码器都支持)具有不同编码的文本文件。问题是编码是在文件指定的——在第一行,像这样:

ISO8859-2 33847 60 minut|10 a|67 a có¿ dopiero|122 a figê|170 ...

如您所见,此特定文件的编码是ISO8859-2。据我所知,我们应该使用open 函数指定编码,以便能够从文件中读取。不指定编码,文件对象的readline() 方法会抛出UnicodeDecodeError。但是如果我一开始就无法读取它,我无法弄清楚如何从文件的第 1 行获取编码。

我希望有一个解决这个明显难题的方法。如有任何帮助,我们将不胜感激。

谢谢。

【问题讨论】:

    标签: python-3.x character-encoding


    【解决方案1】:

    使用选项errors="surrogateescape" 打开文件以抑制错误。然后你就可以读取应该是 ASCII 可读的第一行了。

    # create a test file in ISO-8859-2 with the header
    import codecs
    
    filename = "iso8859-2.txt"
    header = codecs.encode("ISO8859-2\n")
    textBytes = bytearray((32,33,171,187)) # using graphems Ť and ť
    
    # the dictionary to translate your headers to valid encoding strings
    encodings = { "ISO8859-2": "ISO-8859-2" }
    encoding = ""
    
    with open(filename, "wb") as f:
        f.write(header)
        f.write(textBytes)
    
    # yes, it's unreadable !!
    try:
        with open(filename) as f:
            f.readline()
    except: 
        print("right, wrong encoding")
    
    # use the option "surrogateescape"
    with open(filename, encoding="ascii", errors="surrogateescape") as f:
        encoding = f.readline()[0:-1]
    
    # and succeed
    with open(filename, encoding=encodings[encoding]) as f:
        print(f.readline())
        print(f.readline())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 2016-12-29
      • 2015-04-07
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多