Create a file in a specified directory

18,042

The following code checks that the directory you've passed in exists (pulling the directory from the path using File.dirname), and creates it if it does not. It then creates the file as you did before.

require 'fileutils'

def create_file(path, extension)
  dir = File.dirname(path)

  unless File.directory?(dir)
    FileUtils.mkdir_p(dir)
  end

  path << ".#{extension}"
  File.new(path, 'w')
end
Share:
18,042
bAN
Author by

bAN

Software developer interested in everything that can bring a solution to a problem :-)

Updated on June 15, 2022

Comments

  • bAN
    bAN almost 2 years

    How can I create a new file in a specific directory. I created this class:

    class FileManager
    
        def initialize()
    
        end
    
        def createFile(name,extension)
            return File.new(name <<"."<<extension, "w+")
        end
    end
    

    I would like to specify a directory (path) where to create the file. If this one doesn't exist, he will be created. So do I have to use fileutils as shown here just after file creation or can I specify directly in the creation the place where create the file?

    Thanks