如何使用Ruby将列标题写入csv文件? [英] How to write columns header to a csv file with Ruby?

查看:208
本文介绍了如何使用Ruby将列标题写入csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用Ruby将列写入csv文件。下面是我的代码片段。

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

 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.

推荐答案

我建议使用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

使用 w 选项,你真的需要 a + (例如,数据不能一次全部可用)那么你可以尝试以下技巧:

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

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
  }
}

这篇关于如何使用Ruby将列标题写入csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆