Search code examples
pythoncodeclistdircp1252charmap

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


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>

Solution

  • 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))