Nat*_*May 3 python unicode encoding utf-8 python-3.x
我正在遍历文件夹并收集要加载到数据库中的文档名称和其他一些数据。
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')
Run Code Online (Sandbox Code Playgroud)
问题是某些文档名称包含外来字符,例如:
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
Run Code Online (Sandbox Code Playgroud)
和
RC-1046 ??2013ARTISTRY??????-?????????_????????Suit & Tie?.mp4
Run Code Online (Sandbox Code Playgroud)
上面的代码在最后一行给了我这个错误:
UnicodeEncodeError: 'charmap' codec can't encode characters at positions ##-##:character maps to (undefined)
Run Code Online (Sandbox Code Playgroud)
我试过
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为什么不写进去呢?
由于它是 Python 3,请选择支持所有 Unicode 的编码。至少在 Windows 上,默认值依赖于语言环境,例如cp1252,并且对于中文等字符将失败。
text_file = open("Output.txt", "w", encoding='utf8')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1931 次 |
| 最近记录: |