marcamillion marcamillion - 1 year ago 55
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:"#{city}.csv", "a+") do |csv|
csv << listing

But, ideally I would like to do
, if that file doesn't exist.

What's the best way to approach this?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download