csv 文件写入
require 'csv'title = ["col1", "col2"]
contents = [["row11", "row12"], ["row21", "row22"]]csv1 = CSV.open("test1.csv", "wb") do |csv|# write file titlecsv << title# write file bodycontents.each do |line|csv << lineend
endputs csv1.class
puts csv1.inspect# UTF-8编码的文件,开头会加入BOM来表明编码方式
csv2 = CSV.generate("\xEF\xBB\xBF") do |csv|# write file titlecsv << title# write file bodycontents.each do |line|csv << lineend
end
File.open("test2.csv", "wb"){|f| f << csv2}puts csv2.class
puts csv2.inspect
Array
[["row11", "row12"], ["row21", "row22"]]
String
"col1,col2\nrow11,row12\nrow21,row22\n"
csv 文件读取
require 'csv'csv3 = []
CSV.open("test1.csv") do |csv|csv.each do |line|csv3 << lineend
endputs csv3.class
puts csv3.inspectcsv4 = []
File.open("test2.csv", "rb") do |f|f.each do |line|csv4 << lineend
end
puts csv4.class
puts csv4.inspect
Array
[["col1", "col2"], ["row11", "row12"], ["row21", "row22"]]
Array
["\xEF\xBB\xBFcol1,col2\n", "row11,row12\n", "row21,row22\n"]