简体   繁体   English

如何在路径的上下文中使用“~”(波浪号)?

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

I'm a web application development noob.我是 web 应用程序开发菜鸟。 I have a function that opens a file and reads it.我有一个 function 可以打开一个文件并读取它。 Unfortunately, the directory structures between the test and production servers differ.不幸的是,测试服务器和生产服务器之间的目录结构不同。 I was told to "use a path relative to ~".有人告诉我“使用相对于〜的路径”。 I haven't been able to find any resources on the '~', though!但是,我无法在“~”上找到任何资源!

How do I use the tilde character in the context of paths?如何在路径的上下文中使用波浪号?

EDIT: This is in Python.编辑:这是在 Python 中。 I fixed the problem, using os.path.expanduser('~/path/in/home/area') .我使用os.path.expanduser('~/path/in/home/area')解决了这个问题。

it is your $HOME var in UNIX, which usually is /home/username . 它是UNIX中的$HOME var,通常是/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 “你的家”意味着正在执行像cd ~/MyDocuments/这样的命令的用户的家是cd /home/user_executing_cd_commnd/MyDocuments

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. 除非您正在编写shell脚本或使用其他语言知道将$HOME的值替换为~ ,否则文件路径中的波形符号没有特殊含义,将被视为任何其他非特殊字符。

If you are writing a shell script, shells don't interpret tildes unless they occur as the first character in an argument. 如果您正在编写shell脚本,则shell不会解释tildes,除非它们作为参数中的第一个字符出现。 In other words, ~/file will become /path/to/users/home/directory/file , but ./~/file will be interpreted literally (ie, "a file called file in a subdirectory of . called ~ "). 换句话说, ~/file将成为/path/to/users/home/directory/file ,但./~/file将字面解释(即,“一个名为file中的子目录.~ ”)。

Used in URLs, interpretation of the tilde as a shorthand for a user's home directory (eg, http://www.foo.org/~bob ) is a convention borrowed from Unix. 在URL中使用,将波浪号解释为用户主目录的简写(例如, http://www.foo.org/~bobhttp://www.foo.org/~bob )是从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. 实现完全是服务器特定的,因此您需要检查Web服务器的文档,看它是否有任何特殊含义。

如果您使用pathlib作为文件名,那么您可以在Windows和Linux上使用(我来这里是为了获得Windows答案):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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