Mike Maxwell
Mike Maxwell

Reputation: 617

Python relpath /home/<username> vs. ~

In Python3.4 (and also 2.6), using the os.path.relpath cmd, I get different answers if I run:
os.path.relpath("~/foo/bar.txt", "~")
than if I run
os.path.relpath("~/foo/bar.txt", "/home/<username>/")
(where I replace <username> with my user name, naturally!)

Namely, if I'm in my home directory, in the first case I get
foo/bar.txt
(as I would expect), but in the second case I get
~/foo/bar.txt
which is not what I would expect, given that ~ is exactly /home/<username>. (I get the same result in the second case regardless of whether I include the trailing '/' in the second arg.)

The second case gives an even more bizarre result if I run this within a subdirectory of my home directory, say ~/Data/:
Data/~/foo/bar.txt
which unless I'm mistaken is a non-existent directory.

I can figure out a work-around for this, but what is the logic for why it's happening this way? I don't suppose it's a bug, since it's been around a long time.

Upvotes: 0

Views: 149

Answers (1)

icktoofay
icktoofay

Reputation: 129001

~ isn’t actually always your home directory—that’s only your shell’s interpretation. You can create a directory named ~ anywhere you want, just as you could create a directory named orange. Since ~ could be a plain old directory name, Python is treating it that way.

If you want Python to interpret ~ as meaning the home directory, as a shell would do, you need to tell Python you want to replace ~ with the path to the home directory using os.path.expanduser before passing your directory names to relpath.

Upvotes: 2

Related Questions