使用Ruby CSV更改导出的CSV中的字段分隔符/分隔符

是否可以将默认字段分隔符从逗号更改为其他字符,例如'|'以进行导出?

Vincent asked 2020-01-23T09:58:29Z
3个解决方案
105 votes

这是使用标签代替的示例。

到文件:

CSV.open("myfile.csv", "w", {:col_sep => "\t"}) do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

到字符串:

csv_string = CSV.generate(:col_sep => "\t") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

这是有关CSV的当前文档:[http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html]

Dylan Markow answered 2020-01-23T09:59:06Z
8 votes

先前的CSV库在Ruby 1.9中已替换为FasterCSV。

require "csv"

output = CSV.read("test.csv").map do |row|
  row.to_csv(:col_sep => "|")
end
puts output
Lri answered 2020-01-23T09:59:26Z
4 votes

CSV::Writer具有generate方法,该方法接受分隔符字符串作为参数。

#!/usr/bin/env ruby

# +++ ruby 1.8 version +++

require "csv"

outfile = File.open('csvout', 'wb')
  CSV::Writer.generate(outfile, '|') do |csv|
    csv << ['c1', nil, '', '"', "\r\n", 'c2']
  end
outfile.close
miku answered 2020-01-23T09:59:46Z
translate from https://stackoverflow.com:/questions/4821843/changing-field-separator-delimiter-in-exported-csv-using-ruby-csv