如何将外文编码字符写入文本文件。

3
我正在遍历文件夹并收集文档名称和其他一些数据,以便加载到数据库中。
import os
text_file = open("Output.txt", "w")

dirName = 'D:\\'
for nextDir, subDir, fileList in os.walk(dirName):
    for fname in fileList: 
        text_file.write(fname + '\n')

问题在于一些文档名称包含有外语字符,例如:

RC-0964_1000 Tưởng thưởng Diamond trẻ nhất Việt Nam - Đặng Việt Thắng và Trần Thu Phương

并且
RC-1046 安麗2013ARTISTRY冰上雅姿盛典-愛里歐娜.薩維琴科_羅賓.索爾科維【Suit & Tie】.mp4

上述代码在最后一行出现了以下错误:

UnicodeEncodeError: 'charmap' codec can't encode characters at positions ##-##:character maps to (undefined)

我尝试过以下方法:
  • temp = fname.endcode(utf-8)
  • temp = fname.decode(utf-8)
  • temp = fname.encode('ascii','ignore') temp2 = temp.decode('ascii')
  • temp =unicode(fname).encode('utf8')
我该如何编写脚本才能将所有字符写入文件中? 我需要更改正在写入的文件还是正在写入的字符串,以及如何更改?
这些名称可以成功粘贴到文件中,为什么Python无法将它们写入文件呢?

2
你正在使用哪个版本的Python? - Rockybilly
我正在使用3.4版本。 - Nate May
可能是重复的问题:Python:如何将Unicode文本写入文本文件? - roeland
2个回答

6

因为这是Python 3,所以选择支持Unicode的编码。在Windows上,默认情况下会根据语言环境选择编码,例如cp1252,对于中文等字符将无法处理。

text_file = open("Output.txt", "w", encoding='utf8')

我简直不敢相信它是如此简单。谢谢! - Nate May

1

默认情况下,text_file 使用 locale.getpreferredencoding(False)(在你的情况下为 Windows ANSI 代码页)。

os.walk() 在 Windows 上如果输入路径是 Unicode,则使用 Unicode API,因此可能会生成无法使用 Windows 代码页(如 cp1252)表示的名称,导致 UnicodeEncodeError: 'charmap' codec can't encode 错误。8位编码(如 cp1252)只能表示256个字符,但有超过一百万个 Unicode 字符。

为了解决这个问题,使用可以表示给定名称的字符编码。utf-8、utf-16 字符编码可以表示所有 Unicode 字符。例如,在 Windows 上你可能更喜欢使用 utf-16,这样 notepad.exe 就可以正确显示文件:

with open('output.txt', 'w', encoding='utf-16') as text_file:
    print('\N{VICTORY HAND}', file=text_file)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接