0

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 \, but "...Google\ drive".decode('string_escape') != "...Google\ Drive".

Any ideas?

Community
  • 1
  • 1
connorwstein
  • 305
  • 2
  • 13

1 Answers1

0

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.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176