我要遍历文件夹并收集文档名称和其他一些要加载到数据库中的数据。
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为什么不将它们写入其中?
由于它是Python 3,因此请选择一种支持所有Unicode的编码。至少在Windows上,默认值取决于语言环境,例如cp1252
,并且对于中文这样的字符将失败。
text_file = open("Output.txt", "w", encoding='utf8')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句