How to create directories recursively in ruby?

后端 未结 6 1890
醉酒成梦
醉酒成梦 2020-12-02 13:54

I want to store a file as /a/b/c/d.txt, but I do not know if any of these directories exist and need to recursively create them if necessary. How can one do this in ruby?

相关标签:
6条回答
  • 2020-12-02 14:23

    Use mkdir_p to create directory recursively

    path = "/tmp/a/b/c"
    
    FileUtils.mkdir_p(path) unless File.exists?(path)
    
    0 讨论(0)
  • 2020-12-02 14:27

    Pathname to the rescue!

    Pathname('/a/b/c/d.txt').dirname.mkpath
    
    0 讨论(0)
  • 2020-12-02 14:37

    Use mkdir_p:

    FileUtils.mkdir_p '/a/b/c'
    

    The _p is a unix holdover for parent/path you can also use the alias mkpath if that makes more sense for you.

    FileUtils.mkpath '/a/b/c'
    

    In Ruby 1.9 FileUtils was removed from the core, so you'll have to require 'fileutils'.

    0 讨论(0)
  • 2020-12-02 14:40
     require 'ftools'
    

    File.makedirs

    0 讨论(0)
  • 2020-12-02 14:46

    If you are running on unixy machines, don't forget you can always run a shell command under ruby by placing it in backticks.

    `mkdir -p /a/b/c`
    
    0 讨论(0)
  • 2020-12-02 14:46

    You could also use your own logic

    def self.create_dir_if_not_exists(path)
      recursive = path.split('/')
      directory = ''
      recursive.each do |sub_directory|
        directory += sub_directory + '/'
        Dir.mkdir(directory) unless (File.directory? directory)
      end
    end
    

    So if path is 'tmp/a/b/c' if 'tmp' doesn't exist 'tmp' gets created, then 'tmp/a/' and so on and so forth.

    0 讨论(0)
提交回复
热议问题