开发者

os.path.exists not working properly on Python CLI

开发者 https://www.devze.com 2023-03-20 05:41 出处:网络
I\'ve Python 2.5.x on my Windows 7 machine. os.path.exists(\'C:\')# returns True os.path.exists(\'C:\\Users\')# returns True

I've Python 2.5.x on my Windows 7 machine.

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

I've give开发者_JAVA百科n read/write permissions to the CLI I'm using. What could be the possible reason for this ?


Inside quotes, '\' escapes the next character; see the reference on string literals. Either double your backslashes like:

os.path.exists('C:\\Users\\ALPHA')

to escape the backslashes themselves, use forward slashes as path separators as Michael suggests, or use "raw strings":

os.path.exists(r'C:\Users\ALPHA')

The leading r will cause Python not to treat the backslashes as escape characters. That's my favorite solution to dealing with Windows pathnames because they still look like people expect them to.


Use either double backslashes, or forward slashes:

os.path.exists('C:/Users/ALPHA')    
0

精彩评论

暂无评论...
验证码 换一张
取 消