如果 Ruby 不存在,则创建目录 [英] Create Directory if it doesn't exist with Ruby
问题描述
我正在尝试使用以下代码创建目录:
I am trying to create a directory with the following code:
Dir.mkdir("/Users/Luigi/Desktop/Survey_Final/Archived/Survey/test")
unless File.exists?("/Users/Luigi/Desktop/Survey_Final/Archived/Survey/test")
但是,我收到此错误:
没有这样的文件或目录 -/Users/Luigi/Desktop/Survey_Final/Archived/Survey/test (Errno::ENOENT)
No such file or directory - /Users/Luigi/Desktop/Survey_Final/Archived/Survey/test (Errno::ENOENT)
为什么这个目录不是由上面的 Dir.mkdir
语句创建的?
Why is this directory not being created by the Dir.mkdir
statement above?
推荐答案
您可能正在尝试创建嵌套目录.假设 foo
不存在,您将收到 no such file or directory
错误:
You are probably trying to create nested directories. Assuming foo
does not exist, you will receive no such file or directory
error for:
Dir.mkdir 'foo/bar'
# => Errno::ENOENT: No such file or directory - 'foo/bar'
要一次性创建嵌套目录,需要FileUtils
:
To create nested directories at once, FileUtils
is needed:
require 'fileutils'
FileUtils.mkdir_p 'foo/bar'
# => ["foo/bar"]
Edit2:你不必使用FileUtils
,你可以做系统调用(@mu 更新太短注释):
you do not have to use FileUtils
, you may do system call (update from @mu is too short comment):
> system 'mkdir', '-p', 'foo/bar' # worse version: system 'mkdir -p "foo/bar"'
=> true
但这似乎(至少对我而言)是更糟糕的方法,因为您正在使用在某些系统上可能不可用的外部工具"(尽管我很难想象没有 mkdir
的系统,但谁知道).
But that seems (at least to me) as worse approach as you are using external 'tool' which may be unavailable on some systems (although I can hardly imagine system without mkdir
, but who knows).
这篇关于如果 Ruby 不存在,则创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!