如何跳过CSV文件的第一行并将第二行作为标题

5
有没有办法跳过CSV文件的第一行,并让第二行作为标题?
我有一个CSV文件,第一行是日期,第二行是标题,所以我需要在迭代时能够跳过第一行。我尝试使用slice但这会将CSV转换为数组,我确实希望读取它作为CSV,以便利用标题。

你的输入数据是什么?你希望输出数据看起来像什么?你编写的最小代码演示了你想要做什么,为什么它不起作用?或者,你希望有人为你编写代码吗? - the Tin Man
6个回答

7

根据你的数据,你可以使用skip_lines选项来采用另一种方法。

这个例子跳过所有以#开头的行。

require 'csv'

CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
    :skip_lines=> /^#/  #Mark comments!
  ) do |row|
  p row
end
#~ 
__END__
#~ Comment
#~ More comment
a;b;c;d
1;2;3;4
#~ More comment
1;2;3;4
#~ More comment
1;2;3;4

结果是:
#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">
#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">
#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">

在您的情况下,csv文件包含日期信息,因此您可以使用以下方法:
require 'csv'

CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
    :skip_lines=> /^\d\d\d\d-\d\d-\d\d$/  #Skip line with date only
  ) do |row|
  p row
end
#~ 
__END__
2016-03-19
a;b;c;d
1;2;3;4
1;2;3;4
1;2;3;4

或者您可以使用更多的扩展起始行:

require 'csv'

CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
    :skip_lines=> /^Created by/  #Skip line with date only
  ) do |row|
  p row
end

__END__
Created by test.rb on 2016-03-19
a;b;c;d
1;2;3;4
1;2;3;4
1;2;3;4

4
我认为没有一种优雅的方法来做到这一点,但它是可以实现的:
require "csv"

# Create a stream using the original file.
# Don't use `textmode` since it generates a problem when using this approach.
file = File.open "file.csv"

# Consume the first CSV row.
# `\r` is my row separator character. Verify your file to see if it's the same one.
loop { break if file.readchar == "\r" }

# Create your CSV object using the remainder of the stream.
csv = CSV.new file, headers: true

1
你可以做到这个。
text = File.readlines("file.csv")[1..-1].join()
csv = CSV.parse(text, headers: true)

0

我遇到了同样的问题(除了我想跳过开头超过1行),在寻找一个好的解决方案时,我看到了这个问题。对于我的情况,我采用了类似问题的这个答案中描述的代码,只是我还使用了你提到想要使用的headers选项。

CSV.parse(File.readlines(path).drop(1).join, headers: true) do |row|
  # ... now I can use: row['column_name']
end

0
为了后人:有时候第一行存在,但是值为空(在标题之前有一个带有,,,,,,,,,,的行),所以解决方法是通过执行以下操作来删除它们:
require 'csv'

CSV.parse(content, headers: true, skip_lines: /^(\s*,\s*)*$/)

这个解决方案将有效,无论标题之前有多少行为空值。它还将删除标题后的任何空行,因此请注意仔细检查是否适用于您。
附言:如果您正在使用其他字符进行分隔,请更改逗号(,)。

-1

这段简单的代码对我很有用。你可以读取一个CSV文件并忽略它的第一行,也就是标题或字段名称:

CSV.foreach(File.join(File.dirname(__FILE__), filepath), headers: true) do |row|
    puts row.inspect
end

您可以随意使用 row。不要忘记使用 headers: true


问题询问如何处理一个 CSV 文件,其中第一行不是标题,而是一些要忽略的垃圾数据:标题在第二行。 - Wayne Conrad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接