Search code examples
pythonpython-3.xlistdir

python misreading filepath name


I want to iterate over a number of files in the L: drive on my computer in a folder called 11109. This is my script:

for filename in os.listdir('L:\11109'):
    print(filename.split('-')[1])

However the error message comes back as :

File "L:/OMIZ/rando.py", line 12, in <module>
for filename in os.listdir('L:\11109'):

FileNotFoundError: [WinError 3] The system cannot find the path specified: 
'L:I09'

Its reading the L:\ 11109 fine but the error message said the path specified is L:I09?


Solution

  • You need to use raw strings or escape the backslash, otherwise \111 is resolved to I:

    a = 'L:\11109'
    print(a)  # shows that indeed 'L:I09'
    
    b = r'L:\11109'
    print(b)  # prints 'L:\11109'
    
    c = 'L:\\11109'  # will be understood correctly by open()