Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 827
Deepak Lamichhane Avatar asked May 09 '11 11:05

Deepak Lamichhane


People also ask

How do I ignore headers when reading CSV?

To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method.

How do you skip a header line in Python?

Use open(file) to open file . Call next(file) to skip the first line of the file.

How do I skip the first line while reading a CSV file in Python?

Line 1: We import the Pandas library as a pd. Line 2: We read the csv file using the pandas read_csv module, and in that, we mentioned the skiprows=[0], which means skip the first line while reading the csv file data. Line 4: Now, we print the final dataframe result shown in the above output without the header row.

How do I remove the first row from a CSV file?

Use drop() method and pass the index of the fetched row as a parameter in the drop method.


4 Answers

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
like image 90
DMH Avatar answered Sep 19 '22 04:09

DMH


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})
like image 26
David Barlow Avatar answered Oct 06 '22 19:10

David Barlow


csv = CSV.read("file")

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

csv # <-- the results that you want
like image 6
Cheng Avatar answered Oct 06 '22 21:10

Cheng


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
like image 1
Deepak Lamichhane Avatar answered Oct 06 '22 20:10

Deepak Lamichhane