How do I use '~' (tilde) in the context of paths?

前端 未结 3 2000
不知归路
不知归路 2020-12-08 00:38

I\'m a web application development noob. I have a function that opens a file and reads it. Unfortunately, the directory structures between the test and production servers di

相关标签:
3条回答
  • 2020-12-08 00:46

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

    python from pathlib import Path p = Path('~').expanduser() print(p)

    0 讨论(0)
  • 2020-12-08 00:49

    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

    0 讨论(0)
  • 2020-12-08 01:06

    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.

    0 讨论(0)
提交回复
热议问题