Python os.listdir和带转义字符

时间:2015-06-26 03:03:01

标签: python

我有一个字符串变量,我从一个文件中读取了一个包含转义字符的路径,即

dir="...Google\\ Drive"

然后我想用os.listdir列出该路径中的所有文件和目录,即

os.listdir(dir)

但是我得到了这个错误(因为我真的只想逃脱一次):

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

我尝试过使用

os.listdir(r'....Google\ Drive')

os.listdir(dir.replace("\\","\"))

os.listdir(dir.decode('string_escape'))

一切都无济于事。我读了这个Python Replace \\ with \,但是“... Google \ drive”.decode('string_escape')!=“... Google \ Drive”。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果路径可以是任意路径,您可以使用\\拆分字符串,删除任何可能的路径,然后执行os.path.join,示例 -

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

然后你可以在os.listdir()中使用它来列出目录。