Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将外来编码字符写入文本文件_Python_Python 3.x_Unicode_Encoding_Utf 8 - Fatal编程技术网

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)