Get list of files in directory return encode error for persian files name

156 Views Asked by At

When I want to execute simple line of code to get a list of files in one drive i have encountered with encoding error I have a list of files with persian name. when it comes to list these files name raised an encoding error!

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>
3

There are 3 best solutions below

4
On BEST ANSWER

Try:

import os
files_list = os.listdir(r'D:')
print(files_list)

If that doesn't work try using os.walk() instead

for root, dirs, files in os.walk(r'D:'):
    # select file name
    for file in files:
        print(os.path.join(root, file))
3
On

Try encoding it as utf-8

encoded_list = [x.encode("utf-8") for x in os.listdir('DriveName:')]
print(encoded_list)

FYI this question has been answered here UnicodeEncodeError: 'charmap' codec can't encode characters

0
On

Instead of visual studio code I have just tried another IDE like jupyter notebook to execute my codes and it works! it supports persian file names with the code that mentioned by @No blyat