Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open files relative to home directory

Tags:

ruby

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:

  1. Why doesn't open process the tilde as pointing to the home directory?
  2. Is there a slicker way than File.expand_path?
like image 777
Peter Avatar asked Mar 24 '10 00:03

Peter


People also ask

What is the path to home directory?

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.

How do I change a folder using relative path?

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 ...

What is a relative path to a file?

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.

How do I open a file with relative path?

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.


2 Answers

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") 
like image 91
allesklar Avatar answered Oct 24 '22 01:10

allesklar


  1. 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 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...
  2. 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.

like image 29
Roadmaster Avatar answered Oct 24 '22 01:10

Roadmaster