如何打开相对于主目录的文件 [英] How to open files relative to home directory
本文介绍了如何打开相对于主目录的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下失败,Errno::ENOENT: No such file or directory
,即使文件存在:
The following fails with Errno::ENOENT: No such file or directory
, even if the file exists:
open('~/some_file')
但是,我可以这样做:
open(File.expand_path('~/some_file'))
我有两个问题:
- 为什么
open
不将波浪号处理为指向主目录? - 有没有比
File.expand_path
更巧妙的方法?
- Why doesn't
open
process the tilde as pointing to the home directory? - Is there a slicker way than
File.expand_path
?
推荐答案
- 外壳(bash、zsh 等)负责通配符扩展,因此在您的第一个示例中没有外壳,因此没有扩展.使用波浪号指向
$HOME
只是一种约定;实际上,如果您查看File.expand_path
的文档,它会正确解释波浪号,但它是函数本身的一个特性,而不是底层系统固有的特性;此外,File.expand_path
需要正确设置$HOME
环境变量.这给我们带来了可能的替代方案...... 试试这个:
- The shell (bash, zsh, etc) is responsible for wildcard expansion, so in your first example there's no shell, hence no expansion. Using the tilde to point to
$HOME
is a mere convention; indeed, if you look at the documentation forFile.expand_path
, it correctly interprets the tilde, but it's a feature of the function itself, not something inherent to the underlying system; also,File.expand_path
requires the$HOME
environment variable to be correctly set. Which bring us to the possible alternative... Try this:
open(ENV['HOME']+'/some_file')
我希望它足够光滑.我个人认为使用环境变量在语义上比使用 expand_path
更清晰.
I hope it's slick enough. I personally think using an environment variable is semantically clearer than using expand_path
.
这篇关于如何打开相对于主目录的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文