How can you parse only the first line of a CSV file?

How can you parse only the first line of a CSV file? I want to make sure that all relevant columns are specified in the file, but do not want to process the entire file.

+7
ruby ruby-on-rails
source share
3 answers

The best way to do this is to simply use the built-in Enumerable support in the Ruby Standard Library CSV analyzer :

headers = CSV.open('file.csv', 'r') { |csv| csv.first } 

The block will automatically close the file, and the call will return an array of parsed headers.

+15
source share

I figured this out and hope he can help someone else:

  # Return true if the headers match on file1 and file2 def compare_csv_files(file1, file2) file1_first_line = CSV.parse File.open(file1) {|f| f.readline} file2_first_line = CSV.parse File.open(file2) {|f| f.readline} return file1_first_line == file2_first_line end 
+1
source share

Given the file "foo.csv" on your computer:

 # Return true if the headers match on file1 and file2 def compare_csv_files(file1, file2) CSV.parse( File.open(file1).first ) == CSV.parse( File.open(file2).first ) end 
0
source share

All Articles