Python os.listdir and path with escape character
Question: I have a string variable that I have read from a file which is a path that
contains an escape character i.e.

    
    
    dir="...Google\\ Drive"
    

I would like to then list all the files and directories in that path with
os.listdir i.e.

    
    
    os.listdir(dir)
    

But I get this error (because I really only want one escape):

    
    
    OSError: [Errno 2] No such file or directory: '....Google\\ Drive/'
    

I have tried using

    
    
    os.listdir(r'....Google\ Drive')
    
    os.listdir(dir.replace("\\","\"))
    
    os.listdir(dir.decode('string_escape'))
    

all to no avail. I read this [Python Replace \\\ with
\](http://stackoverflow.com/questions/5186839/python-replace-with), but
"...Google\ drive".decode('string_escape') != "...Google\ Drive".

Any ideas?


Answer: If the path could be arbitrary , you can split the the strings using `\\`
removing any '' you may get along the way and then do `os.path.join` , Example
-

    
    
    >>> import os.path
    >>> l = "Google\Drive\\\\ Temp"
    >>> os.path.join(*[s for s in l.split('\\') if l != ''])
    'Google\\Drive\\ Temp'
    

Then you can use that in os.listdir() to list the directories.

