如果在ruby中使用'csv'庫,如何替換標頭而不重新讀取文件?如何替換CSV標頭
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錶轉換爲數組數組來改變頭,但是我不知道該怎麼做。
在你的例子中,你正在閱讀一個csv,寫入另一個,閱讀第二個另一次,並最終將其打印爲一個字符串。你是否想要與不同的標題完全相同的內容?所需的輸出是最後一個片段? – Anthony 2014-11-05 02:51:08
我已經添加了一些代碼註釋,應該更好地說明這一點。我試圖在一個不太笨重的莊園中用「dur」,「hur」,「whur」替換「日期」,「foo」,「酒吧」。 – spuder 2014-11-05 02:58:23
爲什麼不在文件的最初讀取中,用'headers:true'跳過標題,並且只是寫下你想要的標題在新的csv中? – Anthony 2014-11-05 03:17:37