如何跳过CSV文件的第一行,使第二行为标题 [英] How to skip the first line of a CSV file and make the second line the header

查看:565
本文介绍了如何跳过CSV文件的第一行,使第二行为标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法跳过CSV文件的第一行,使第二行作为标题?

Is there a way to skip the first line of a CSV file and make the second line act as the header?

我有一个CSV文件,其日期在第一行和第二行的标题,所以我需要能够跳过第一行时迭代它。我尝试使用 slice 但是将CSV转换为数组,我真的想读它为CSV,所以我可以利用标题。

I have a CSV file that has the date on the first row and the headers on the second row, so I need to be able to skip the first row when iterating over it. I tried using slice but that converts the CSV to an array and I really want to read it as CSV so I can take advantage of headers.

推荐答案

我不认为有一种优雅的做法,但可以这样做:

I don't think there's an elegant way of doing it, but it can be done:

require "csv"

# Create a stream using the original file.
# Don't use `textmode` since it generates a problem when using this approach.
file = File.open "file.csv"

# Consume the first CSV row.
# `\r` is my row separator character. Verify your file to see if it's the same one.
loop { break if file.readchar == "\r" }

# Create your CSV object using the remainder of the stream.
csv = CSV.new file, headers: true

这篇关于如何跳过CSV文件的第一行,使第二行为标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆