The following fails with Errno::ENOENT: No such file or directory
, even if the file exists:
open('~/some_file')
However, I can do this:
open(File.expand_path('~/some_file'))
I have two questions:
open
process the tilde as pointing to the home directory?File.expand_path
?By default, all non-root user home directories are located in a directory named "home", below the / (root) directory - in the path of /home. For example, for a Linux user named cwest, the home directory is in the path of /home/cwest. The home directory for the bbest user is in the path of /home/bbest.
To change directories using absolute pathnames, type cd /directory/directory; to change directories using relative pathnames, type cd directory to move one directory below, cd directory/directory to move two directories below, etc.; to jump from anywhere on the filesystem to your login directory, type cd; to change to ...
Relative Path is the hierarchical path that locates a file or folder on a file system starting from the current directory. The relative path is different from the absolute path, which locates the file or folder starting from the root of the file system.
Opening a File with Relative Path In the relative path, it will look for a file into the directory where this script is running. # Opening the file with relative path try: fp = open("sample. txt", "r") print(fp. read()) fp.
Not sure if this was available before Ruby 1.9.3 but I find that the most elegant solution is to use Dir.home
which is part of core.
open("#{Dir.home}/some_file")
$HOME
is a mere convention; indeed, if you look at the documentation for File.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')
I hope it's slick enough. I personally think using an environment variable is semantically clearer than using expand_path
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With