有没有办法跳过CSV文件的第一行,并让第二行作为标题?
我有一个CSV文件,第一行是日期,第二行是标题,所以我需要在迭代时能够跳过第一行。我尝试使用
我有一个CSV文件,第一行是日期,第二行是标题,所以我需要在迭代时能够跳过第一行。我尝试使用
slice
但这会将CSV转换为数组,我确实希望读取它作为CSV,以便利用标题。根据你的数据,你可以使用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">
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
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
text = File.readlines("file.csv")[1..-1].join()
csv = CSV.parse(text, headers: true)
我遇到了同样的问题(除了我想跳过开头超过1行),在寻找一个好的解决方案时,我看到了这个问题。对于我的情况,我采用了类似问题的这个答案中描述的代码,只是我还使用了你提到想要使用的headers选项。
CSV.parse(File.readlines(path).drop(1).join, headers: true) do |row|
# ... now I can use: row['column_name']
end
,,,,,,,,,,
的行),所以解决方法是通过执行以下操作来删除它们:require 'csv'
CSV.parse(content, headers: true, skip_lines: /^(\s*,\s*)*$/)
这段简单的代码对我很有用。你可以读取一个CSV文件并忽略它的第一行,也就是标题或字段名称:
CSV.foreach(File.join(File.dirname(__FILE__), filepath), headers: true) do |row|
puts row.inspect
end
您可以随意使用 row
。不要忘记使用 headers: true