Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 551 Vote(s) - 3.43 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create Directory if it doesn't exist with Ruby

#1
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)

Why is this directory not being created by the `Dir.mkdir` statement above?
Reply

#2
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'

To create nested directories at once, `FileUtils` is needed:

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

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

#3
Another simple way:

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

#4
How about just `Dir.mkdir('dir') rescue nil` ?
Reply

#5
Simple way:

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



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through