59

To fix a problem in code for work, I was told to "use a path relative to ~". What does ~ mean in a file path? How can I make a path that is relative to ~, and use that path to open files in Python?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
captcadaver
  • 1,093
  • 2
  • 9
  • 7
  • I can think of two perfectly correct but completely different answers to this, depending on what you are doing your web application development **with**. Indeed, the completely different answers so far given cover those, but nobody can be sure which is right, or if it isn't a third one. Please edit your question to include the technology used. – Jon Hanna Aug 15 '10 at 18:35
  • You fixed the problem ~ it would have been nice if you had posted some sample code – Mawg says reinstate Monica Jan 23 '15 at 09:12

3 Answers3

46

it is your $HOME var in UNIX, which usually is /home/username.

"Your home" meaning the home of the user who's executing a command like cd ~/MyDocuments/ is cd /home/user_executing_cd_commnd/MyDocuments

dierre
  • 7,140
  • 12
  • 75
  • 120
19

Unless you're writing a shell script or using some other language that knows to substitute the value of $HOME for ~, tildes in file paths have no special meaning and will be treated as any other non-special character.

If you are writing a shell script, shells don't interpret tildes unless they occur as the first character in an argument. In other words, ~/file will become /path/to/users/home/directory/file, but ./~/file will be interpreted literally (i.e., "a file called file in a subdirectory of . called ~").

Used in URLs, interpretation of the tilde as a shorthand for a user's home directory (e.g., http://www.foo.org/~bob) is a convention borrowed from Unix. Implementation is entirely server-specific, so you'd need to check the documentation for your web server to see if it has any special meaning.

Blrfl
  • 6,817
  • 1
  • 25
  • 25
13

If you are using pathlib for filenames then you can use on both Windows and Linux (I came here for a windows answer):

from pathlib import Path
p = Path('~').expanduser()
print(p)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
hum3
  • 1,563
  • 1
  • 14
  • 21
  • 1
    See https://stackoverflow.com/questions/10487827/why-am-i-forced-to-os-path-expanduser-in-python for why this is necessary. – Karl Knechtel Sep 29 '22 at 02:26