如何将阵列保存为CSV文件?

时间:2016-02-19 01:49:16

标签: ruby csv web-scraping web-crawler

我有一个webcrawl脚本和一个scraper脚本。当我整合这两个时,我可以从每个网页获得我想要的数组,但我无法将其保存为CSV文件。我尝试了这段代码,但它不起作用:

CSV.open("scraper.csv", "wb") do |csv|
          csv << ["date", "venue", "time", "race_number", "race_name", "track", "purse"]
          csv << $race_data = [date, venue, time, race_number, race_name, track, purse]
end

嗯,它确实保存了一个CSV文件,但该文件只是继续覆盖自己,而不是仅仅使用一个文件,而是在其上。

1 个答案:

答案 0 :(得分:0)

找到了答案。问题是我的CSV.open在“w”中,用新数据覆盖文件。所以,来自

CSV.open("scraper.csv", "wb") do |csv|
      csv << ["date", "venue", "time", "race_number", "race_name", "track", "purse"]
      csv << $race_data = [date, venue, time, race_number, race_name, track, purse]
end

我这样说:

CSV.open("scraper.csv", "ab") do |csv|
      csv << ["date", "venue", "time", "race_number", "race_name", "track", "purse"]
      csv << $race_data = [date, venue, time, race_number, race_name, track, purse]
end