csv文件简介
逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。
CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。
csv文件可以用文本编辑器打开,也可以用excel和wps类软件打开。
ruby如何处理csv文件
1,ruby有一个标准库用于处理csv文件,在代码中引入即可:
require ‘csv’
2,写csv文件的2个方法
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
3,读取csv文件的2个方法
一次读入一行:
CSV.foreach(“path/to/file.csv”) do |row|
# use row here…
end
一次读入全部文件:
arr_of_arrs = CSV.read(“path/to/file.csv”)
一次读入全部文件后,可以再用each方法逐行处理:
CSV.open(“path/to/file.csv”, “rb”).each do |row|
# use row here…
end
4,实例
任意找一个路径,打开irb,即可运行如下示例代码。
2.1.1 :001 > filename = “books.csv”
“books.csv”
2.1.1 :002 > require ‘csv’
true
2.1.1 :003 > CSV.open(filename, “wb”) do |csv|
2.1.1 :004 > csv << [“name”, “price”]
2.1.1 :005?> csv << [“How to learn ruby”, 12.34]
2.1.1 :006?> csv << [“How to learn C++”, 10.11]
2.1.1 :007?> end
<#CSV io_type:File io_path:”books.csv” encoding:ASCII-8BIT lineno:3 col_sep:”,” row_sep:”\n” quote_char:”\”“>
2.1.1 :008 >
2.1.1 :009 > CSV.foreach(filename, headers: true) do |row|
2.1.1 :010 > puts row
2.1.1 :011?> puts “name: #{row[“name”]}, price: #{row[“price”]}”
2.1.1 :012?> end
How to learn ruby,12.34
name: How to learn ruby, price: 12.34
How to learn C++,10.11
name: How to learn C++, price: 10.11
nil
2.1.1 :013 > CSV.foreach(filename, headers: true) do |row|
2.1.1 :014 > puts row.class
2.1.1 :015?> end
CSV::Row
CSV::Row
nil
2.1.1 :016 > CSV.open(filename, “rb”) do |row|
2.1.1 :017 > puts row
2.1.1 :018?> end
nil
2.1.1 :019 > CSV.open(filename, “rb”).each_line do |row|
2.1.1 :020 > puts row.class
2.1.1 :021?> end
NoMethodError: undefined method each_line' for #<CSV:0x00000001d15848>
’
from (irb):19
from /home/liukun/.rvm/rubies/ruby-2.1.1/bin/irb:11:in
2.1.1 :022 > CSV.open(filename, “rb”).each do |row|
2.1.1 :023 > puts row.class
2.1.1 :024?> puts row
2.1.1 :025?> end
Array
name
price
Array
How to learn ruby
12.34
Array
How to learn C++
10.11
nil
2.1.1 :026 > CSV.open(filename, “rb”).each do |row|
2.1.1 :027 > p row
2.1.1 :028?> end
[“name”, “price”]
[“How to learn ruby”, “12.34”]
[“How to learn C++”, “10.11”]
nil
2.1.1 :029 >
2.1.1 :030 >
2.1.1 :031 >
2.1.1 :032 > CSV.generate(“books_tow.csv”) do |csv|
2.1.1 :033 > csv << [“name”, “price”]
2.1.1 :034?> csv << [“Chinese”, 12.11]
2.1.1 :035?> csv << [“English”, 11.22]
2.1.1 :036?> end
“books_tow.csvname,price\nChinese,12.11\nEnglish,11.22\n”
2.1.1 :037 >
5,参考资料
ruby官方文档
http://ruby-doc.org/stdlib-2.3.0/libdoc/csv/rdoc/CSV.html