Question

In Python, can I be sure the expanded user call will be an absolute path if the path has "~" in it?

For example, is this expression always true?

path = '~/.my_app'
os.path.expanduser(path) == os.path.abspath(os.path.expanduser(path))
Was it helpful?

Solution

It depends on what your $HOME points to. On most properly set-up systems (every mainstream Linux distro, OSX and Windows) it'll point to an absolute path, e.g. /home/user or C:/Users/User. But if it's unset, improperly set or even changed manually (export HOME=.), expanduser may result in a relative path, in which case abspath will further change it.

But for most intents and purposes, you can assume that yes, both expressions are equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top