如果使用' csv' ruby中的库,如何在不重新读取文件的情况下替换标题?
foo.csv
'date','foo',bar'
1,2,3
4,5,6
使用CSV ::表格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表转换为数组数组来更改标题,但是我不知道该怎么做。
答案 0 :(得分: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"]]