I'm trying to take a CSV file, strip a few columns, and then output a pipe delimited text file.
我正在尝试获取CSV文件,删除几列,然后输出管道分隔的文本文件。
Here's my code, which almost works. The only problem is the CSV.generate
block is adding double quotes around the whole thing, as well as a random comma with double quotes around it where the line break is.
这是我的代码,几乎可以工作。唯一的问题是CSV.generate块在整个事物周围添加双引号,以及在换行符周围的双引号随机逗号。
require 'csv'
original = CSV.read('original.csv', { headers: true, return_headers: true })
original.delete('Column header 1')
original.delete('Column header 2')
original.delete('Column header 3')
csv_string = CSV.generate do |csv|
csv << original
end
pipe_string = csv_string.tr(",","|")
File.open('output.txt', 'w+') do |f|
f.write(pipe_string)
end
Is there a better way to do this? Any help is appreciated.
有一个更好的方法吗?任何帮助表示赞赏。
1 个解决方案
#1
3
Try this:
require 'csv'
original = CSV.read('original.csv', { headers: true, return_headers: true })
original.delete('Column header 1')
original.delete('Column header 2')
original.delete('Column header 3')
CSV.open('output.txt', 'w', col_sep: '|') do |csv|
original.each do |row|
csv << row
end
end
#1
3
Try this:
require 'csv'
original = CSV.read('original.csv', { headers: true, return_headers: true })
original.delete('Column header 1')
original.delete('Column header 2')
original.delete('Column header 3')
CSV.open('output.txt', 'w', col_sep: '|') do |csv|
original.each do |row|
csv << row
end
end