os.path.exists在Python CLI上无法正常工作

hal*_*tTm 2 python python-module

我的Windows 7机器上有Python 2.5.x.

os.path.exists('C:')              # returns True
os.path.exists('C:\Users')        # returns True
os.path.exists('C:\Users\alpha')  # returns False, when ALPHA is a user on my machine
Run Code Online (Sandbox Code Playgroud)

我给了我正在使用的CLI的读/写权限.可能的原因是什么?

Kir*_*ser 5

在引号内,'\'转义下一个字符; 请参阅字符串文字参考.要么加倍你的反斜杠,如:

os.path.exists('C:\\Users\\ALPHA')
Run Code Online (Sandbox Code Playgroud)

若要逃避反斜杠本身,请使用正斜杠作为迈克尔建议的路径分隔符,或使用"原始字符串":

os.path.exists(r'C:\Users\ALPHA')
Run Code Online (Sandbox Code Playgroud)

领先r将导致Python不将反斜杠视为转义字符.这是我最喜欢的处理Windows路径名的解决方案,因为它们看起来仍然像人们期望的那样.