Errno::ENOENT: No such file or directory ruby

You can't save to a non-existing path. As the developer you're responsible to make sure your destination paths exist prior to trying to save the file.

Ruby has methods that let you check for the existence a file or directory:

  • File.exist?('path/to/file')
  • File.file?('path/to/file')
  • File.directory?('path/to/file')
  • Dir.directory?('path/to/dir')
  • Dir.mkdir('path/to/dir')
  • FileUtils.makedirs('path/to/dir')

FileUtils.makedirs() is an alias to mkpath, and mkdir_p. I prefer makedirs because it's a mnemonic.

These will also be useful:

  • Dir.chdir('path/to/dir')
  • FileUtils.chdir('path/to/dir')

Between those two I prefer Dir.chdir, because it takes a block. Any actions that occur inside that block happen in the directory you changed to. At exit, the directory reverts to what it was previously.


The analog of *nix mkdir -p, mkdir_p, is what you need, which was provided in the other two answers, but I didn't see anyone address your edit about permissions.

The solution is the user invoking your script requires write permission on the root directory.

The path, "/a/b/c", is addressing the root path ("/"). This is typically only write accessible to the root user or a user that has sudo access.

When you modified the path to remove the leading "/", you told mkdir_p to create the directories "a/b/c" relative to the current working directory instead of relative to the root directory. The reason the modified version works is because the user invoking your ruby script has write permission on the current working directory.

As a personal aside, if consumers of your script are providing the path input, then you probably don't want to remove leading slashes as that can create files/directories in a drastically different place from where the user expects...unless that is the purpose of your program, but make that clear up front.

References:

  • *nix-style permissions
  • sudo

I got here because I had gem installed but the file was not installed on the machine. In my case, I had gem espeak-ruby gem was installed but it was not installed on my mac so I installed that with simple brew install espeak command and restarted the server. My recommendation to you us make sure everything is installed properly.

Tags:

Ruby