12.5. How to Process a CSV File

Problem

You want to process the lines in a CSV file, either handling one line at a time or storing them in a two-dimensional array.

Solution

Combine Recipe 12.1 with Recipe 1.3. Given a simple CSV file like this named finance.csv:

January, 10000.00, 9000.00, 1000.00
February, 11000.00, 9500.00, 1500.00
March, 12000.00, 10000.00, 2000.00

you can process the lines in the file with the following code:

object CSVDemo extends App {

  println("Month, Income, Expenses, Profit")
  val bufferedSource = io.Source.fromFile("/tmp/finance.csv")
  for (line <- bufferedSource.getLines) {
    val cols = line.split(",").map(_.trim)
    // do whatever you want with the columns here
    println(s"${cols(0)}|${cols(1)}|${cols(2)}|${cols(3)}")
  }
  bufferedSource.close

}

The magic in that code is this line:

val cols = line.split(",").map(_.trim)

It splits each line using the comma as a field separator character, and then uses the map method to trim each field to remove leading and trailing blank spaces. The resulting output looks like this:

January|10000.00|9000.00|1000.00
February|11000.00|9500.00|1500.00
March|12000.00|10000.00|2000.00

If you prefer named variables instead of accessing array elements, you can change the for loop to look like this:

for (line <- bufferedSource.getLines) {
  val Array(month, revenue, expenses, profit) = line.split(",").map(_.trim)
  println(s"$month $revenue $expenses $profit")
}

If the first line of the file is a header line and you want to skip it, just add drop(1) after ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.