2014-11-05 53 views
0

如果在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錶轉換爲數組數組來改變頭,但是我不知道該怎麼做。

+1

在你的例子中,你正在閱讀一個csv,寫入另一個,閱讀第二個另一次,並最終將其打印爲一個字符串。你是否想要與不同的標題完全相同的內容?所需的輸出是最後一個片段? – Anthony 2014-11-05 02:51:08

+0

我已經添加了一些代碼註釋,應該更好地說明這一點。我試圖在一個不太笨重的莊園中用「dur」,「hur」,「whur」替換「日期」,「foo」,「酒吧」。 – spuder 2014-11-05 02:58:23

+1

爲什麼不在文件的最初讀取中,用'headers:true'跳過標題,並且只是寫下你想要的標題在新的csv中? – Anthony 2014-11-05 03:17:37

回答

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"]] 
+0

謝謝,但是代碼已經在使用CSV.table(),所以頭文件被創建了一個符號,因此允許使用delete_if()。這可以通過CSV.table()完成https://github.com/spuder/simple-ynab/blob/eddf9871a30daaab0938b08f882ff7a789f6db56/tests/doublearray.rb – spuder 2014-11-09 22:01:52