【问题标题】:How to replace CSV headers如何替换 CSV 标头
【发布时间】:2014-11-05 02:35:45
【问题描述】:

如果在 ruby​​ 中使用“csv”库,如何在不重新读取文件的情况下替换标题?

foo.csv

'date','foo',bar'
1,2,3
4,5,6

使用 CSV::Table because of this answer

这是一个可行的解决方案,但是它需要从文件中写入和读取两次。

require 'csv'
@csv = CSV.table('foo.csv')

# Perform additional operations, like remove specific pieces of information. 

# Save fixed csv to a file (with incorrect headers)
File.open('bar.csv','w') do |f|
  f.write(@csv.to_csv)
end

# New headers
new_keywords = ['dur','hur', 'whur']

# Reopen the file, replace the headers, and print it out for debugging
# Not sure how to replace the headers of a CSV::Table object, however I *can* replace the headers of an array of arrays (hence the file.open)
lines = File.readlines('bar.csv')
lines.shift
lines.unshift(new_keywords.join(',') + "\n")
puts lines.join('')

# TODO: re-save file to disk

如何在不从磁盘读取两次的情况下修改标头?

'dur','hur','whur'
1,x,3
4,5,x

更新
对于那些好奇的人,here is the unabridged code。为了使用delete_if() 之类的东西,必须使用 CSV.table() 函数导入 CSV。

也许可以通过将 csv 表转换为数组数组来更改标题,但是我不知道该怎么做。

【问题讨论】:

  • 在您的示例中,您正在读取一个 csv,写入另一个,再次读取第二个并最终将其全部打印为字符串。您是否想要具有不同标题的完全相同的内容?期望的输出是最后一个 sn-p 吗?
  • 我添加了一些代码 cmets,应该可以更好地阐明这一点。我正在尝试用“dur”、“hur”、“whur”替换“date”、“foo”、“bar”,而不是那么笨重的庄园。
  • 为什么不在文件的初始读取中,跳过带有headers: true 的标题,只写你希望标题在新 csv 中的内容?
  • 我在 csv 表上做一些需要知道表头是什么的操作。

标签: ruby csv


【解决方案1】:

给定一个 test.csv 文件,其内容如下所示:

id,name,age
1,jack,8
2,jill,9

您可以使用以下方法替换标题行:

require 'csv'

array_of_arrays = CSV.read('test.csv')

p array_of_arrays # => [["id", "name", "age"],
                  # =>  ["1", "jack", "26"],
                  # =>  ["2", "jill", "27"]]    

new_keywords = ['dur','hur','whur']

array_of_arrays[0] = new_keywords

p array_of_arrays # => [["dur", "hur", "whur"],
                  # =>  ["1", " jack", " 26"],
                  # =>  ["2", " jill", " 27"]]

或者,如果您希望保留原来的二维数组:

new_array = Array.new(array_of_arrays)
new_array[0] = new_keywords

p new_array # => [["dur", "hur", "whur"],
            # =>  ["1", " jack", " 26"],
            # =>  ["2", " jill", " 27"]]

p array_of_arrays # => [["id", "name", "age"],
                  # =>  ["1", "jack", "26"],
                  # =>  ["2", "jill", "27"]]

【讨论】:

  • 谢谢,但是代码已经在使用 CSV.table() 以便标题创建一个符号,从而允许使用 delete_if()。这可以用 CSV.table() github.com/spuder/simple-ynab/blob/… 完成吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 2019-10-01
  • 1970-01-01
  • 2019-02-26
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多