Question

Simple code:

import os 

filenamelist = []
#path = "E:\blah\blah\blah"
path = "C:\Program Files\Console2"
for files in os.walk(path):
    filenamelist.append(files)
    print files

The above works. But when I set path= "E:\blah\blah\blah" the script runs but returns nothing.

1) C:\Users\guest>python "read files.py"

('C:\\Program Files\\Console2', [], ['console.chm', 'Console.exe', 'console.xml', 'ConsoleHook.dll', 'FreeImage.dll', 'FreeImagePlus.dll'])

2) C:\Users\guest>python "read files.py"

C:\Users\guest>

Any idea why os.walk() is having a difficult time with E:\? I can't get it to read anything on E:. I have an external drive mapped to E drive.

Was it helpful?

Solution

That could be because python treats \ as an escape symbol and you have a combination that is really an escape symbol for E: disk path.

It might be solved in one of the following ways:

  1. Raw string literals: r"E:\blah\blah\blah" (the backslashes are not treated as escape symbols).
  2. Double-backslashes: "E:\\blah\\blah\\blah" (escape symbols are escaped by themselves).
  3. Slashes "E:/blah/blah/blah" (this works on Windows too).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top