Created
June 7, 2012 08:21
-
-
Save jofi/2887383 to your computer and use it in GitHub Desktop.
CSV manipulation in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
# http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html | |
# READING !!!FROM FILE!!!! | |
# Line by Line: | |
CSV.foreach('csvfile.csv') do | |
|row| | |
puts row #array | |
end | |
# All at once: | |
array_of_arrays = CSV.read('csvfile.csv') | |
# READING !!!FROM STRING!!!!! | |
# Line by line: | |
str = File.read('csvfile.csv') | |
CSV.parse(str) do | |
|row| | |
puts row #array | |
end | |
# All at once: | |
array_of_arrays = CSV.parse(str) | |
# WRITING | |
# To a file | |
CSV.open("csvfile_out.csv", "wb", col_sep: ";") do |csv| | |
csv << ["row", "of", "CSV", "data"] | |
csv << ["another", "row"] | |
# ... | |
end | |
# To a string | |
str = CSV.generate do |csv| | |
csv << ["row", "of", "CSV", "data"] | |
csv << ["another", "row"] | |
# ... | |
end | |
puts str | |
# OPTIONS (defaults): | |
# :col_sep | |
# "," | |
# | |
# :row_sep | |
# :auto | |
# | |
# :quote_char | |
# '"' | |
# | |
# :field_size_limit | |
# nil | |
# | |
# :converters | |
# nil | |
# | |
# :unconverted_fields | |
# nil | |
# | |
# :headers | |
# false | |
# | |
# :return_headers | |
# false | |
# | |
# :header_converters | |
# nil | |
# | |
# :skip_blanks | |
# false | |
# | |
# :force_quotes | |
# false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment