13

How can the header line of the CSV file be ignored in ruby on rails while doing the CSV parsing!! Any ideas

David Barlow
  • 4,914
  • 1
  • 28
  • 24
Deepak Lamichhane
  • 19,076
  • 4
  • 30
  • 42
  • 1
    What exactly is your question? To skip the Headerline simply start at line 1 instead of 0 – sra May 09 '11 at 11:28
  • 1
    btw, don't forget that you will need the header to identify the content of the CVS. Otherwise you just have data without knowing what exactly – sra May 09 '11 at 11:31

6 Answers6

26

If you're using ruby 1.8.X and FasterCSV, it has a 'headers' option:

csv = FasterCSV.parse(your_csv_file, {:headers => true}) #or false if you do want to read them

If you're using ruby 1.9.X, the default library is basically FasterCSV, so you can just do the following:

csv = CSV.parse(your_csv_file, {headers: true})
David Barlow
  • 4,914
  • 1
  • 28
  • 24
  • 4
    watch-out as `CSV.parse your_csv_content` and `CSV.parse your_csv_content, headers: true` returns different objects . First is array of arrays, second is array of `CSV::Row` objects http://stackoverflow.com/a/37856698/473040 – equivalent8 Jun 16 '16 at 10:37
6
csv = CSV.read("file")

csv.shift # <-- kick out the first line

csv # <-- the results that you want
Cheng
  • 4,816
  • 4
  • 41
  • 44
1

Easier way I have found is by doing this:

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
DMH
  • 2,529
  • 3
  • 24
  • 35
1

Here is the simplest one worked for me. You can read a CSV file and ignore its first line which is the header or field names using headers: true:

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

You can do what ever you want with row. Don't forget headers: true

Aboozar Rajabi
  • 1,683
  • 21
  • 26
1

I have found the solution to above question. Here is the way i have done it in 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
Deepak Lamichhane
  • 19,076
  • 4
  • 30
  • 42
0

To skip the header without the headers option (since that has the side-effect of returning CSV::Row rather than Array) while still processing a line at a time:

File.open(path, 'r') do |io|
  io.readline
  csv = CSV.new(io, headers: false)
  while row = csv.shift do
    # process row
  end
end
jjg
  • 907
  • 8
  • 18