Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何替换CSV文件中的标题?_Ruby_Csv - Fatal编程技术网

Ruby 如何替换CSV文件中的标题?

Ruby 如何替换CSV文件中的标题?,ruby,csv,Ruby,Csv,我是ruby的新手,对编程也相当陌生 如何更改csv文件的标题 foo, bar, foobar 1, 2, 3, 4, 5, 6, 7, 8, 9, 改为: herp, derp, herpaderp 1, 2, 3, 4, 5, 6, 7, 8, 9, 但是,我发现它并不真正适用,因为我使用的是内置的“csv”库,而不是旧的“fastcsv”库。(在Mac OSX上使用ruby 2.0.0) 我试过的 require 'csv

我是ruby的新手,对编程也相当陌生

如何更改csv文件的标题

foo, bar, foobar
1,   2,   3,
4,   5,   6,
7,   8,   9,
改为:

herp, derp, herpaderp
1,    2,    3,
4,    5,    6,
7,    8,    9, 
但是,我发现它并不真正适用,因为我使用的是内置的“csv”库,而不是旧的“fastcsv”库。(在Mac OSX上使用ruby 2.0.0)

我试过的

require 'csv'
@filename = ARGV[0]
new_headers = ["herp", "derp", "herpaderp"]

origional_csv = CSV.read(@filename, {headers: true, return_headers: true })
headers = CSV.open(@filename, 'r', :headers => true).read.headers
puts headers

#Change headers to new_headers ? 
使用foo.csv文件从命令行调用test.rb

$ ruby test.rb foo.csv
foo, bar, foobar

您甚至不需要在CSV库中执行此操作。只需更改文件的第一行,其余的输出相同:

lines = File.readlines(@filename)
lines.shift
lines.unshift(["herp", "derp", "herpaderp"].join(',') + "\n")
puts lines.join('')

我认为,在同一个文件中更新是不可能的。我说得对吗?需要从一个文件复制数据,在处理数据后,将这些数据发送到新文件。除非标题文本的长度完全相同,否则无法就地更新。通常最好还是重新写入另一个文件,以防你把事情搞砸了。