Ivan Ivan - 1 year ago 82
Scala Question

In Scala, how to read a simple CSV file having a header in it's first line?

The task is to look for a specific field (by it's number in line) value by a key field value in a simple CSV file (just commas as separators, no field-enclosing quotes, never a comma inside a field), having a header in it's first line.

User uynhjl has given an example (but with a different character as a separator):

val src = Source.fromFile("/etc/passwd")
val iter = src.getLines().map(_.split(":"))
// print the uid for Guest
iter.find(_(0) == "Guest") foreach (a => println(a(2)))
// the rest of iter is not processed

the question in this case is how to skip a header line from parsing?

Answer Source

You can just use drop:

val iter = src.getLines().drop(1).map(_.split(":"))

From the documentation:

def drop (n: Int) : Iterator[A]: Advances this iterator past the first n elements, or the length of the iterator, whichever is smaller.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download