1

How to use listdir to list all files in a directory in windows. I need to list all files in the location C:\Users\jibin\Desktop\CDR\CDR_Extract\, it gives an error "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape"

import os
arr = os.listdir('C:\Users\jibin\Desktop\CDR\CDR_Extract')
print(arr)
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
Jibin
  • 424
  • 2
  • 4
  • 15
  • 2 potential problems: (1) incorrect indentation - Python uses indentation to define code blocks (2) escape sequences in path - use a raw string instead - https://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-and-what-are-raw-string-literals – moo Apr 28 '20 at 10:46

2 Answers2

3

You need to escape the backslashes in the string.

Replace:

'C:\Users\jibin\Desktop\CDR\CDR_Extract'

With (escape the backslashes),

'C:\\Users\\jibin\\Desktop\\CDR\\CDR_Extract'

Or, use forward slashes instead of backlashes,

'C:/Users/jibin/Desktop/CDR/CDR_Extract'

Or, you can put r in front of string to convert normal string to raw string,

r'C:\Users\jibin\Desktop\CDR\CDR_Extract'
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
0

you can use glob module, see the example bellow (its generic approach for listing and doing some thing with files you want to locate)

import glob
import os

def rmf_handler(arg,cdir,names):
    # for example we want to remove *.pyc files from current directory
    for path in glob.glob(cdir+'\*.pyc'):
        print 'remove {ppath}'.format(ppath=path)
        os.remove(path)

def rmm(root):
    os.path.walk(root,rmf_handler,None)

# call it:
rmm(root_dir)
Adam
  • 2,820
  • 1
  • 13
  • 33