tags:

views:

264

answers:

2

I read my csv using the line below

data = FCSV.table("test.csv", {:quote_char => '"', :col_sep =>',', :row_sep =>:auto, :headers => true, :return_headers => false, :header_converters => :downcase, :converters => :all} )

QUESTION

Can I save object data in the same manner (one line, one go + csv options)? see above

I sort the table (see the code below) and then I want so save it again. I couldn't work out how to save the table in one go. I know how to do it row by row though.

array_of_arrays = data.to_a()
headers = array_of_arrays.shift # remove the headers
array_of_arrays.sort_by {|e| [e[3], e[4].to_s, e[1]]} .each {|line| p line }
array_of_arrays.insert(0,headers)

Anything I tried did not work and gave me something very similar to

csv.rb:33: syntax error, unexpected '{', expecting ')'
... FCSV.table("sorted.csv","w" {:quote_char => '"', :col_sep =...

NOTE:

Please note that I want to use all the CSV options when saving the file {:quote_char => '"', :col_sep =>',', :row_sep =>:auto, :headers => true, :return_headers => false, :header_converters => :downcase, :converters => :all}

A: 

Since you've got an array of arrays in data, it looks like you can just do:

FCSV::Table.new(data).to_csv

to get all the csv for data as a string, then output that back to the file.

dunedain289
@dunedain289: and the bit `back to the file` is something I am asking about
Radek
+1  A: 

Just following up on what dunedain said, the following will write the file out

@csv = FCSV::Table.new(data).to_csv
File.open("modified_csv.csv", 'w') {|f| f.write(@csv) }

also the error you had in the code below is because you didnt have a comma after the "w" and before the { but it looks like you were perhaps tring to the reader functions instead of the writer functions

csv.rb:33: syntax error, unexpected '{', expecting ')'
... FCSV.table("sorted.csv","w" {:quote_char => '"', :col_sep =...
ADAM
@Adam: thank for the comma thing.FCSV.table takes only two arguments not three so I won't work anyway. Please note that I want to save csv file and use csv options at the same time.
Radek
no probs, can you post some more code around the FCSV.table("sorted.csv" .... not just the errors?
ADAM
@Adam: I added the source code...
Radek