Life In The Stack Trace...

TODO: <Insert clever marketing phrase here>

Golang - Read a file line by line

Golang - Read a file line by line

Reading a file line by line in Golang is pretty easy. Have a look at the following example:

package main

import (
  "bufio"
  "log"
  "os"
)

func main() {

  // open a file
  if file, err := os.Open("test.txt"); err == nil {

    // make sure it gets closed
    defer file.Close()

    // create a new scanner and read the file line by line
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        log.Println(scanner.Text())
    }

    // check for errors
    if err = scanner.Err(); err != nil {
      log.Fatal(err)
    }

  } else {
    log.Fatal(err)
  }

}

I don't know how it could be more straight forward. Open a file, create a scanner to read the file, actually read the file line by line, then close.

Too easy Drill Sergeant!!

Download the support file and run the example.

Duck