Deepak Lamichhane
Deepak Lamichhane

Reputation: 22644

Ignore header line when parsing CSV file

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

Upvotes: 14

Views: 14075

Answers (6)

jjg
jjg

Reputation: 1024

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

Upvotes: 0

Aboozar Rajabi
Aboozar Rajabi

Reputation: 1793

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

Upvotes: 1

DMH
DMH

Reputation: 2809

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

Upvotes: 1

David Barlow
David Barlow

Reputation: 4974

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})

Upvotes: 26

Cheng
Cheng

Reputation: 4886

csv = CSV.read("file")

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

csv # <-- the results that you want

Upvotes: 6

Deepak Lamichhane
Deepak Lamichhane

Reputation: 22644

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

Upvotes: 1

Related Questions