Errno::ENOENT: 没有那个文件或目录 ruby [英] Errno::ENOENT: No such file or directory ruby
问题描述
我收到以下错误:
"Errno::ENOENT: No such file or directory"
当我尝试将文件下载到不存在的目录时.
when I try to download a file into a directory that does not exist.
例如:
ftp = Net::FTP.new('example.com')
ftp.login
files = ftp.chdir('pub/lang/ruby/contrib')
files = ftp.list('n*')
ftp.getbinaryfile('nif.rb-0.91.gz', 'pub/lang/ruby/contrib/nif.gz', 1024)
ftp.close
但是,对于我将要下载的许多文件,完整的目录路径将不存在.例如,在第一个文件创建 pub 之前,它不会存在,这也适用于 lang/ruby/contrib.
However, for many of the files I will be downloading, the full directory path will not exist. For example, until the first file creates pub, it won't exist and this goes for lang/ruby/contrib too.
有没有一种方法可以检查目录是否存在,如果不存在则创建它们?我知道存在吗?,但这看起来是参考文件,它不会创建完整路径.我想我需要一些递归方法来遍历文件夹结构,直到遇到文件名.
Is there a method that can check if directories exist and if not create them? I know that there is exist?, but that looks to reference files and it does not create the full path. I figure I need some recursive method to traverse down the folder structure until it hits the filename.
mkdir_p 似乎正是我需要的解决方案.
mkdir_p seems to be exactly the solution I need.
但是,当我使用/a/b/c"路径时,我注意到FileUtils.mkdir_p(File.dirname(localdir))返回错误:Errno::EACCES: Permission denied -/a
However, when I use a path of "/a/b/c" I noticed that FileUtils.mkdir_p(File.dirname(localdir)) returns an error: Errno::EACCES: Permission denied - /a
如果我手动删除前面的/",它会起作用.这是什么原因造成的?解决错误的最佳解决方案是什么?我应该只使用以下内容吗?
If I remove the "/" in front manually it works. What is causing this? What is the best solution for resolving the error? should I just use the following?
path="/a/b/c"
if path[0]="/"
path=path[1..-1]
end
然而,我觉得这只是一个黑客.
However, I feel like this is just a hack.
推荐答案
您无法保存到不存在的路径.作为开发人员,您有责任在尝试保存文件之前确保目标路径存在.
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 有一些方法可以让您检查文件或目录是否存在:
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/目录')
FileUtils.makedirs()
是 mkpath
和 mkdir_p
的别名.我更喜欢 makedirs
因为它是一个助记符.
FileUtils.makedirs()
is an alias to mkpath
, and mkdir_p
. I prefer makedirs
because it's a mnemonic.
这些也很有用:
在这两者之间我更喜欢 Dir.chdir
,因为它需要一个块.该块内发生的任何操作都发生在您更改的目录中.退出时,目录恢复到以前的状态.
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.
这篇关于Errno::ENOENT: 没有那个文件或目录 ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!