Python 如何将外来编码字符写入文本文件
我在文件夹中递归,收集文档名和一些其他数据,以便加载到数据库中Python 如何将外来编码字符写入文本文件,python,python-3.x,unicode,encoding,utf-8,Python,Python 3.x,Unicode,Encoding,Utf 8,我在文件夹中递归,收集文档名和一些其他数据,以便加载到数据库中 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ư
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
及
上面的代码在最后一行给了我这个错误:
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=临时解码('ascii')
temp=unicode(fname).encode('utf8')
这些名称可以成功粘贴到文件中,那么Python为什么不将它们写入文件中呢?既然是Python 3,请选择一种支持所有Unicode的编码。至少在Windows上,默认值取决于语言环境,例如
cp1252
,对于像中文这样的字符将失败
text_file = open("Output.txt", "w", encoding='utf8')
默认情况下,
text\u文件
使用locale.getpreferredencoding(False)
(在您的情况下为Windows ANSI代码页)
os.walk()
如果输入路径在Windows上是Unicode,则使用Unicode API,因此它可能会生成无法使用Windows代码页(如cp1252)表示的名称,从而导致Unicode编码错误:“charmap”编解码器无法编码
错误。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)
你用的是什么版本的Python?我用的是版本3.4的可能的副本我不敢相信它这么简单。非常感谢。
with open('output.txt', 'w', encoding='utf-16') as text_file:
print('\N{VICTORY HAND}', file=text_file)