Writing an application that accept only csv file with header. So trying to detect is csv file have header or not. Is there any things to do that.
I put some sample data in my test.text file :
name,age,location
Ram,12,UK
Jadu,11,USA
And the code I wrote to check if the header is present or not :-
#!/usr/bin/env ruby
require 'csv'
csv = CSV.open("#{__dir__}/test.txt", :col_sep => ",", :headers => true )
p csv.read.headers
# >> ["name", "age", "location"]
Now this array you have to check, if it matches with your headers values. If it matched, then you can tell, yes header is applied.This code is written exactly on the same base as @tadman said :
here's no standard way of defining headers in a CSV file, but convention dictates that the first line, and only the first line, is headers. People are free to do whatever they want and, in the process, make your life as a developer absolutely miserable.
To know what are these options mean :col_sep, :headers checkout the documentation of CSV::new.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With