在进行CSV解析时,如何在轨道上的ruby中忽略CSV文件的标题行!!任何想法
答案 0 :(得分:26)
如果你使用的是ruby 1.8.X和FasterCSV,它有一个'标题'选项:
csv = FasterCSV.parse(your_csv_file, {:headers => true}) #or false if you do want to read them
如果您使用的是ruby 1.9.X,则默认库基本上是FasterCSV,因此您只需执行以下操作:
csv = CSV.parse(your_csv_file, {headers: true})
答案 1 :(得分:6)
csv = CSV.read("file")
csv.shift # <-- kick out the first line
csv # <-- the results that you want
答案 2 :(得分:3)
忽略标题的一种很酷的方法是将其作为数组读取并忽略第一行:
data = CSV.read("dataset.csv")[1 .. -1]
# => [["first_row", "with data"],
["second_row", "and more data"],
...
["last_row", "finally"]]
:headers => false
方法的问题是CSV
不会尝试将第一行作为标题读取,而是将其视为数据的一部分。所以,基本上,你有一个无用的第一行。
答案 3 :(得分:1)
我找到了上述问题的解决方案。这是我在ruby 1.9.X中完成它的方式。
csv_contents = CSV.parse(File.read(file))
csv_contents.slice!(0)
csv=""
csv_contents.each do |content|
csv<<CSV.generate_line(content)
end
答案 4 :(得分:1)
这是最简单的一个适合我的方法。您可以使用headers: true
CSV.foreach(File.join(File.dirname(__FILE__), filepath), headers: true) do |row|
puts row.inspect
end
您可以使用row
执行任何操作。别忘了headers: true
答案 5 :(得分:0)
我发现的更容易的方法是:
file = CSV.open('./tmp/sample_file.csv', { :headers => true })
# <#CSV io_type:File io_path:"./tmp/sample_file.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"" headers:true>
file.each do |row|
puts row
end