问题
I currently have the following code to parse a csv file using the standard csv library
@parsed_file=CSV::Reader.parse(params[:dump][:file])
@parsed_file.each do |row|
#some code
end
I want to move this to faster csv for the increased speed. Does anyone know the equivalent of the above for FasterCSV?
Thanks
回答1:
CSV::Reader.parse(File.open('file.csv')){|row| puts row}
or
CSV::Reader.parse("some, content\nanother, content"){|row| puts row}
and
FasterCSV.parse(File.open('file.csv')){|row| puts row}
or
FasterCSV.parse("some, content\nanother, content"){|row| puts row}
are equivalent.
But
FasterCSV.read('filename')
takes filename as parameter and reads and parse data from the file however you are dumping the file content as you are passing data in the parameter
@parsed_file = FasterCSV.parse(params[:dump][:file])
@parsed_file.each do |row|
puts row
# and do some operations
end
should work fine.
回答2:
To do it with a file path (as you appear to be):
FasterCSV.read(params[:dump][:file])
You can check the FasterCSV docs for other ways to do it (e.g., process each row as it's parsed, or read from a string instead of a file).
来源:https://stackoverflow.com/questions/2264294/ruby-on-rails-moving-from-csv-to-fastercsv