ruby 如何使用Ruby将列标题写入csv文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15905985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:52:24  来源:igfitidea点击:

How to write columns header to a csv file with Ruby?

rubyruby-on-rails-3csvfastercsv

提问by Joe

I am having trouble writing columns to a csv file with Ruby. Below is my snippet of code.

我在使用 Ruby 将列写入 csv 文件时遇到问题。下面是我的代码片段。

 calc = numerator/denominator.to_f
 data_out = "#{numerator}, #{denominator}, #{calc}"
 File.open('cdhu3_X.csv','a+') do|hdr|
      hdr << ["numerator","denominator","calculation\n"] #< column header
          hdr << "#{data_out}\n"
 end

The code adds the column headers to every line and I only need it at the top of each column of data. I have searched here and other places but can't find a clear answer to how its done. Any help would be greatly appreciated.

该代码将列标题添加到每一行,我只需要在每列数据的顶部使用它。我已经在这里和其他地方搜索过,但找不到关于它是如何完成的明确答案。任何帮助将不胜感激。

回答by knut

I would recommend to use the CSV-library instead:

我建议改用 CSV 库:

require 'csv'

CSV.open('test.csv','w', 
    :write_headers=> true,
    :headers => ["numerator","denominator","calculation"] #< column header
  ) do|hdr|
  1.upto(12){|numerator|
    1.upto(12){ |denominator|
      data_out = [numerator, denominator, numerator/denominator.to_f]
      hdr << data_out
    }
  }
end

If you can't use the woption and you really need the a+(e.g., the data isn't available all at once), then you could try the following trick:

如果您无法使用该w选项并且您确实需要a+(例如,数据并非一次可用),那么您可以尝试以下技巧:

require 'csv'

column_header = ["numerator","denominator","calculation"]
1.upto(12){|numerator|
  1.upto(12){ |denominator|
    CSV.open('test.csv','a+', 
        :write_headers=> true,
        :headers => column_header
      ) do|hdr|
          column_header = nil #No header after first insertion
          data_out = [numerator, denominator, numerator/denominator.to_f]
          hdr << data_out
        end
  }
}

回答by sfstewman

The cleanest way to do this is to open the file once, in mode 'w', write the headers, and then write the data.

最简洁的方法是在 mode 中打开文件一次'w',写入标头,然后写入数据。

If there's some technical reason that can't do this (e.g., the data isn't available all at once), then you can use the IO#tellmethod on the file to return the current file position. When you open the file for appending, the position is set to the end of the file, so if the current file position is zero, then the file was newly created and has no headers:

如果有一些技术原因不能这样做(例如,数据不是一次可用的),那么您可以使用IO#tell文件上的方法返回当前文件位置。当您打开文件进行追加时,位置设置为文件末尾,因此如果当前文件位置为零,则该文件是新创建的并且没有标题:

File.open('cdhu3_X.csv', 'a+') do |hdr|
  if hdr.tell() == 0  # file is empty, so write header
    hdr << "numerator, denominator, calculation\n"
  end
  hdr << "#{data_out}\n"
end

回答by Asad Ali

Best way to handle csv file is to use Ruby's CSVmodule.

处理 csv 文件的最佳方法是使用 Ruby 的CSV模块。

I had same problem after reading CSVcode I came across this solution which i find most efficient.

阅读CSV代码后我遇到了同样的问题,我遇到了这个我认为最有效的解决方案。

headers = ['col1','col2','col3']

CSV.open(file_path, 'a+', {force_quotes: true}) do |csv|
  csv << headers if csv.count.eql? 0 # csv.count method gives number of lines in file if zero insert headers
end