【问题标题】:How to use .write() with characters from foreign languages (ã, à, ê, ó, ...)如何将 .write() 用于外语字符(ã、à、ê、ó、...)
【发布时间】:2020-08-15 15:43:50
【问题描述】:

我正在使用 Python 3 开发一个小项目,我必须扫描一个装满文件的驱动器并输出一个 .txt 文件,其中包含驱动器内所有文件的路径。问题是一些文件是巴西葡萄牙语的,其中有“重音字母”,如“não”、“você”等,而这些特殊字母在最终的 .txt 中输出错误。

代码就是下面这几行:

import glob

path = r'path/path'

files = [f for f in glob.glob(path + "**/**", recursive=True)]

with open("file.txt", 'w') as output:
    for row in files:
        output.write(str(row.encode('utf-8') )+ '\n')

输出示例

path\folder1\Treino_2.doc
path\folder1\Treino_1.doc
path\folder1\\xc3\x81gua de Produ\xc3\xa7\xc3\xa3o.doc

最后一行显示一些输出是错误的,因为x81gua de Produ\xc3\xa7\xc3\xa3o 应该是Régua de Produção

【问题讨论】:

  • 以文本形式打开文件就足够了。您可能想为文件选择一个编码,将encoding 参数设置为open()。您不想手动编码。
  • str(row.encode('utf-8') ) 将值编码为字节,然后将字节对象编码为字符串,而您不想这样做。
  • 当我不这样做时,有时我会收到错误UnicodeEncodeError: 'charmap' codec can't encode
  • 这是您的默认文件编码的问题。
  • 为了将来参考,在您的问题中包含该信息。此外,您的代码的输出没有准确地复制,您还在这些文件中写入b'...',因此使用小写字母b 和引号。这些是在字节对象上使用str() 的结果。

标签: python python-3.x encoding glob


【解决方案1】:

Python 文件直接处理 Unicode 文本(包括巴西重音字符)。您需要做的就是在文本模式下使用该文件,这是默认模式,除非您明确要求open() 给您一个二进制文件。 "w" 给你一个可写的文本文件。

但是,您可能希望通过使用encoding argument for the open() function 来明确编码:

with open("file.txt", "w", encoding="utf-8") as output:
    for row in files:
        output.write(row + "\n")

如果您没有明确设置编码,则使用system-specific default is selected。并非所有编码都可以编码所有可能的 Unicode 代码点。这种情况在 Windows 上比在其他操作系统上发生得更多,默认 ANSI 代码页会导致 charmap codepage can't encode character 错误,但如果当前语言环境配置为使用非 Unicode 编码,它也可能发生在其他操作系统上。

不 编码为字节,然后使用str() 再次将生成的bytes 对象转换回字符串。这只会让字符串表示和转义以及b 前缀变得一团糟:

>>> path = r"path\folder1\Água de Produção.doc"
>>> v.encode("utf8")  # bytes are represented with the "b'...'" syntax
b'path\\folder1\\\xc3\x81gua de Produ\xc3\xa7\xc3\xa3o.doc'
>>> str(v.encode("utf8"))  # converting back with `str()` includes that syntax
"b'path\\\\folder1\\\\\\xc3\\x81gua de Produ\\xc3\\xa7\\xc3\\xa3o.doc'"

请参阅What does a b prefix before a python string mean? 了解更多详情。

【讨论】:

    【解决方案2】:

    您可能只想将文件名字符串直接写入文件,而无需先将它们编码为 UTF-8,因为它们已经 采用这种编码。那就是:

    …
        for row in files:
            output.write(row + '\n')
    

    应该做正确的事。


    我说“可能”,因为在某些操作系统(例如 Linux!)中,文件名不必是有效的 UTF-8,将它们视为 UTF-8 会失败。在这种情况下,您唯一的办法是将文件名作为原始字节序列处理 - 但是,这不会在您的代码中发生,因为 glob 已经返回字符串而不是字节数组,即 Python 已经尝试解码字节序列将文件名表示为 UTF-8。

    您可以告诉glob 通过将通配模式作为字节序列传递来处理任意字节文件名(即非UTF-8)。在 Linux 上,以下工作:

    filename = b'\xbd\xb2=\xbc \xe2\x8c\x98'
    
    with open(filename, 'w') as file:
        file.write('hi!\n')
    
    import glob
    print(glob.glob(b'*')[0])
    # b'\xbd\xb2=\xbc \xe2\x8c\x98'
    
    # BUT:
    print(glob.glob('*')[0])
    #---------------------------------------------------------------------------
    #UnicodeEncodeError                        Traceback (most recent call last)
    #<ipython-input-12-2bce790f5243> in <module>
    #----> 1 print(glob.glob('*')[0])
    #
    #UnicodeEncodeError: 'utf-8' codec can't encode characters in position 0-1: surrogates not allowed
    

    【讨论】:

    • 您对glob() 的建议是红鲱鱼。他们没有对glob()有意见。
    • @MartijnPieters 我知道。对OP的具体回复是我回答的第一部分。我的回答的第二部分是一个一般性的 FYI,很容易 99% 的 Python 代码出错(公平地说,在许多其他语言中也是如此)。
    • 鉴于用户在 Windows 上,并且可能使用a recent Python release,这对他们来说可能不是问题。
    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 2013-07-20
    • 2018-12-10
    • 2011-09-30
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多