当我想执行简单的一行代码来获取一个驱动器中的文件列表时,我遇到了编码错误 我有一个带有波斯语名称的文件列表。当列出这些文件名时,出现了编码错误!
import os
print(os.listdir('D:'))
Traceback (most recent call last):
File "....\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 74-76: character maps to <undefined>
尝试:
import os
files_list = os.listdir(r'D:')
print(files_list)
如果这不起作用,请尝试使用 os.walk() 代替
for root, dirs, files in os.walk(r'D:'):
# select file name
for file in files:
print(os.path.join(root, file))
尝试将其编码为
utf-8
encoded_list = [x.encode("utf-8") for x in os.listdir('DriveName:')]
print(encoded_list)
仅供参考,这个问题已在这里得到解答 UnicodeEncodeError:“charmap”编解码器无法对字符进行编码
我没有尝试使用 Visual Studio 代码,而是尝试使用另一个 IDE(例如 Jupyter Notebook)来执行我的代码,并且它有效!它支持波斯文件名 使用@No blyat
提到的代码