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)
1
  • 2 potential problems: (1) incorrect indentation - Python uses indentation to define code blocks (2) escape sequences in path - use a raw string instead - stackoverflow.com/questions/2081640/… Commented Apr 28, 2020 at 10:46

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.