marcamillion marcamillion - 2 months ago 8
Ruby Question

How do I create a subdirectory if no one exists when writing to a CSV file?

I am creating a CSV file like this:

CSV.open("#{city}.csv", "a+") do |csv|
csv << listing
end


But, ideally I would like to do
results/#{city}.csv
, if that file doesn't exist.

What's the best way to approach this?

Answer

You can do this:

require "fileutils"

csvfile= 'tmp/folder1/folder2/folder3/foo.csv'

FileUtils::mkdir_p File.dirname csvfile

mkdir_p is line gnu mkdir -p which creates the directory structure for you, and won't complain if the directory already exists.

dirname returns the directory name.

If you want specify permissions when creating the directory do this:

FileUtils::mkdir_p( File.dirname(csvfile) , :mode => 0777)
Comments