Skip the first 5 lines of CSV

I'm sure this is trivial, but after age pulled my hair over time, for you friendly people to save me.

I want to work with a CSV file, which I read with the CSV class as follows:

CSV.foreach(@path_to_file) do |row|
    #doing stuff here
end

However, the file has 5 lines above the header to be deleted (the foreachbarfs method when it encounters these lines).

I suppose I can read the file and compile it without the first 5 lines, but I'm sure there is a more elegant way to do this.

The reason CSV methods don't work is because the top 5 lines have characters that the CSV class doesn't like; he returns CSV:MalformedCSVError: Illegal quoting in line 3.

So I don’t think I can use the CSV class unless I can delete it before it tries to parse the CSV.

+1
source share
3 answers

You should be able to get around the CSV module by building the correct CSV string from your incompatible data:

CSV.parse(File.readlines(path).drop(5).join) do |row|
  # ...
end
+6
source
csv = CSV.open @path_to_file
csv.drop(5).each do |row|
  #doing stuff here
end
0
source

:

require 'csv'

CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
  ) do |row|
  p row
end

__END__
a;b;c;d
1;2;3;4
here we have an error because there is a " in the text;
1;2;3;4
"1";"2";3;4

, : Illegal quoting in line 3. (CSV::MalformedCSVError)

, , :skip_lines:

require 'csv'

CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
    :skip_lines=> /a " in the text/
  ) do |row|
  p row
end

__END__
a;b;c;d
1;2;3;4
here we have an error because there is a " in the text;
1;2;3;4
"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 ( "), qoute :

require 'csv'

CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
    quote_char: '§'
  ) do |row|
  p row
end

__END__
a;b;c;d
1;2;3;4
here we have an error because there is a " in the text;
1;2;3;4
"1";"2";3;4

, , (. ):

#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">
#<CSV::Row "a":"here we have an error because there is a \" in the text" "b":nil "c":nil "d":nil>
#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">
#<CSV::Row "a":"\"1\"" "b":"\"2\"" "c":"3" "d":"4">
0

All Articles