← All Articles

How to Read a file in Go

Posted on

In go you will sometimes write more code than you are used to in e.g. most higher level languages (think php, ruby, python) - but will have a lot more control over how it is done.

package main

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

func readLines(path string) ([]string, error) {
  file, err := os.Open(path)
  if err != nil {
    return nil, err
  }
  defer file.Close()

  var lines []string
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    lines = append(lines, scanner.Text())
  }
  return lines, scanner.Err()
}


func main() {
  lines, err := readLines("file.go")
  if err != nil {
    log.Fatalf("readLines: %s", err)
  }
  for i, line := range lines {
    fmt.Println(i+1, line)
  }

}

In this instance we read all the lines of a file (the program itself) into memory - using the bufio.Scanner api instead of naively trying to split the input text on e.g. newlines, and return that as an array of strings. Then we loop through these and print them to the console (prefixed by the line number).

polyglotbitsgoread-a-file