且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Ruby中创建新的CSV文件?

更新时间:2023-11-18 22:39:10

正如mikeb指出的,有文档 - http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html - 或者,您也可以按照下面的示例(所有的测试和工作):

As mikeb pointed out, there are the docs - http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html - Or you can follow along with the examples below (all are tested and working):

在这个文件中,我们将有两行,一个标题行和一个数据行,非常简单的CSV:

In this file we'll have two rows, a header row and data row, very simple CSV:

require "csv"
CSV.open("file.csv", "wb") do |csv|
  csv << ["animal", "count", "price"]
  csv << ["fox", "1", "$90.00"]
end

文件称为file.csv,具有以下内容:

result, a file called "file.csv" with the following:

animal,count,price
fox,1,$90.00






如何将数据附加到CSV



几乎相同的forumla,而不是使用wb模式,我们将使用a +模式。有关这些的详细信息,请参阅此堆栈溢出答案:什么是


How to append data to a CSV

Almost the same forumla as above only instead of using "wb" mode, we'll use "a+" mode. For more information on these see this stack overflow answer: What are the Ruby File.open modes and options?

CSV.open("file.csv", "a+") do |csv|
  csv << ["cow", "3","2500"]
end

打开我们的file.csv我们有:

Now when we open our file.csv we have:

animal,count,price
fox,1,$90.00
cow,3,2500








现在,您知道如何复制和写入文件,读取CSV,因此抓取您刚才所做的操作数据:


Read from our CSV file

Now you know how to copy and to write to a file, to read a CSV and therefore grab the data for manipulation you just do:

CSV.foreach("file.csv") do |row|
  puts row #first row would be ["animal", "count", "price"] - etc.
end

当然,这是一个像一百种不同的方式,你可以使用这个gem从CSV中拉取信息。有关详情,建议您访问文档,现在您有一个底漆: http:/ /ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html

Of course this is like one of like a hundred different ways you can pull info from a CSV using this gem. For more info I suggest visiting the docs now that you have a primer: http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html