Ruby:Update value on specific row but keep the headers
昨天在stackoverflow上问了第一个问题,被鄙视了。。。说“This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form”。。。
问题如下:
I have a csv file with header. I need to update all values in a specific column but keep the header, and then save the file. How can I do it via csv library?
require 'csv' file_name = "path/to/file.csv" CSV.foreach(file_name, {:headers=>true}) do |row| puts row[4] end arr = [] # CSV.foreach(file_name, {:headers=>true}) {|row| arr << row} arr.each do |row| row[4].replace("new program name") end # puts arr ## CSV.open(file_name, "wb", {:headers=>true}) do |csv| csv << ["your", "header", "value"] arr.each {|row| csv << row} end ## CSV.foreach(file_name, {:headers=>true}) do |row| puts row[4] end
作者:Shane
出处:http://bluescorpio.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://bluescorpio.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。