UPDATE BELOW
I have a Ruby script that is looping through some JSON and creating multiple .CSV files with the data. Currently it just creates those in the same folder as script/JSON. However, I want it to create the files in a newly created subdirectory that is timestamped.
I know I need require 'fileutils.rb'
and I created time = Time.now.strftime("%Y%m%d%H%M%S%")
and outdir = FileUtils.mkdir(time)
I added these to my script and it successfully creates the directory but then breaks.
The end of the script that creates the files looks like this and I think the problem is the way I am going about moving into the directory/creating the files in the new dir:
...
outdir = FileUtils.mkdir(time)
FileUtils.cd(outdir) do #I think this is wrong
filename = k+".csv"
out = CSV.open(filename, "w")
csv.each{|item| out << item}
out.close()
end
}
---UPDATE---
It appears the problem is when I am designating the dir path and the CSV module. I am getting the error Invalid argument - ["20130312113853"]/regions.csv (Errono::EINVAL)
When I look at the CSV module docs I see you can declare a path for reading CSVs but nothing on creating/writing to them in another direcotry. This is the first time I have used this module. Does anyone know how to approach this?
I think I need to declare the dir path for csv before csv = []
?
Fullscript:
#!/usr/bin/env ruby
require 'json'
require 'csv'
require 'fileutils.rb'
file = "parse_me.json"
ff = JSON.parse(File.open(file).read)
time = Time.now.strftime("%Y%m%d%H%M%S")
outdir = FileUtils.mkdir(time)
begin
ff.each{|k,h|
csv = []
csv << h[0].keys
h.each{|arr|
holder = []
arr.each_value{|v|
holder << v
}
csv << holder
}
out = CSV.open("#{outdir}/#{k}.csv", "w")
csv.each{|item| out << item}
out.close()
}
end
It's because FileUtils.mkdir
returns an Array
as you can create one or more directories in a same time, it returns an Array
of the directory created..
If you simply work with time
directly, your code should work
...
FileUtils.mkdir(time)
FileUtils.cd(time) do
filename = k+".csv"
out = CSV.open(filename, "w")
csv.each{|item| out << item}
out.close()
end