How can the header li开发者_如何转开发ne of the CSV file be ignored in ruby on rails while doing the CSV parsing!! Any ideas
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})
csv = CSV.read("file")
csv.shift # <-- kick out the first line
csv # <-- the results that you want
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
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
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
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
精彩评论