简体   繁体   中英

os.path.expanduser failing to encode backslash?

In a Python script (executed in 2.7), the second statement returns false, although the directory exists:

from os import path
path.exists( path.expanduser('~') )

I think this is a backslash problem, since path.exists(...) with "hand-coded" home directory using either / or \\\\ returns true, as expected.

This problem seems to be somewhat specific to my machine, as the same script works fine on other computers (also running Windows).

What causes this behaviour? How can it be fixed without hacking the script (which runs fine on most Windows machines)?

Update

The problem is caused by path.expanduser('~') wrapping the path in quotes ( " ) on my system, but not on others.

The basic questions remain: Why?

Can this behaviour be changed on my machine without changing the script (which is not maintained by me and works well for everybody else)?

查看ntpath.py的源代码, expanduser()函数首先尝试按顺序返回环境变量HOME然后返回USERPROFILE ,最后回到HOMEDRIVEHOMEPATH的复合,所以我猜你有引号设置其中一个环境变量。

from os import path
path.exists( path.abspath(path.expanduser('~')) )

Works? (haven't tested but should replace \\ and / issues)

Quote from the Python docs on path.exists() :

Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM