Hi, All,
Suppose I have a CSV file, there is data in it.
Column 1 Column2 Column 3 Column 4
Row1 a b c
Row2 a2 b2 c2
You know, the column 4 is no data
Now, I would like to insert data to Column 4, after save, the CSV file will be:
Column 1 Column2 Column 3 Column 4
Row1 a b c d
Row2 a2 b2 c2 d2
How can I do that?
Any suggestion would be quite appreciated.
Thanks.
Wesley Chen.
Have you looked at the FasterCSV docs?
http://fastercsv.rubyforge.org/classes/FasterCSV.html
Just parse the file and then write to it again with the new column.
When I use
fcsv=FasterCSV.open(“test.csv”, “a+”)
fcsv << “Hello”
I can only add “Hello” to the end row of the csv.
But how can I insert another column to the CSV?
Thanks.
Wesley Chen.
I said open the file, parse it again and re-generate it with the new column:
FasterCSV.open("path/to/file.csv", "w") do |csv|
FasterCSV.foreach("path/to/new/file.csv") do |row|
csv << (row.fields + [ new_column_value ])
end
end