【发布时间】: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 表上做一些需要知道表头是什么的操作。