如果 Ruby 不存在,则创建目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19280341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:14:19  来源:igfitidea点击:

Create Directory if it doesn't exist with Ruby

ruby

提问by Luigi

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")  

However, I'm receiving this error:

但是,我收到此错误:

No such file or directory - /Users/Luigi/Desktop/Survey_Final/Archived/Survey/test (Errno::ENOENT)

没有这样的文件或目录 - /Users/Luigi/Desktop/Survey_Final/Archived/Survey/test (Errno::ENOENT)

Why is this directory not being created by the Dir.mkdirstatement above?

为什么Dir.mkdir上面的语句没有创建这个目录?

回答by zrl3dx

You are probably trying to create nested directories. Assuming foodoes not exist, you will receive no such file or directoryerror for:

您可能正在尝试创建嵌套目录。假设foo不存在,您将收到以下no such file or directory错误:

Dir.mkdir 'foo/bar'
# => Errno::ENOENT: No such file or directory - 'foo/bar'

To create nested directories at once, FileUtilsis needed:

要一次创建嵌套目录,FileUtils需要:

require 'fileutils'
FileUtils.mkdir_p 'foo/bar'
# => ["foo/bar"]

Edit2: you do not have to use FileUtils, you may do system call (update from @mu is too short comment):

Edit2:您不必使用FileUtils,您可以进行系统调用(来自@mu 的更新太短的评论):

> system 'mkdir', '-p', 'foo/bar' # worse version: system 'mkdir -p "foo/bar"'
=> true

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

但这似乎(至少对我而言)是更糟糕的方法,因为您使用的是在某些系统上可能不可用的外部“工具”(尽管我很难想象没有 的系统mkdir,但谁知道呢)。

回答by Licysca

Simple way:

简单的方法:

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

回答by ?tefan Barto?

Another simple way:

另一种简单的方法:

Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')

Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')

回答by Vidar

How about just Dir.mkdir('dir') rescue nil?

刚刚Dir.mkdir('dir') rescue nil怎么样?