#由于headers配置,返回类型发生变化(这个方法默认为第一行是标题,不会进行返回)
CSV.foreach 'test.csv' do |row|
puts row.class#=> Arrayend
CSV.foreach('test.csv', headers:true) do |row|
puts row.class#=> CSV::Rowend
#return_headers:true 返回标题
CSV.foreach('test.csv', return_headers:true) do |row|
p row #=> 返回Array
end
字符串中读取:一次读取一行
CSV.parse("CSV,data,String") do |row|
# use row here...
end
字符串中读取:全部读取
CSV.parse("CSV,data,String")
#[]方法需要返回的类型为CSV::ROW;所以设置参数headers:true
content = File.read('data.csv')
csv = CSV.parse(content, headers:true)
sum = 0
csv.each do |row|
sum += row['id'].to_i
end
puts sum
2.写入csv
写入文件
CSV.open("path/to/file.csv", "wb") do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end
写入字符串
csv_string = CSV.generate do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end #=> "row,of,CSV,data\nanother,row\n"