golang can be used to read files. You can either read a file directly into a string variable or read a file line by line.

These functionality golang provides out of the box is for read files on the hard disk, not on the cloud.

Read files in golang

Read file

The golang program below reads a file from the disk. golang will read the file from the same directory as your program. If the file is in another directory, specify its path.

If you want to read a file at once, you can use:


package main

import (
    "fmt"
        "io/ioutil"
    )

func main() {
    b, err := ioutil.ReadFile("read.go")
    // can file be opened?
    if err != nil {
      fmt.Print(err)
    }

    // convert bytes to string
    str := string(b)

    // show file data
    fmt.Println(str)    
}

This reads the entire file into a golang string.

Line by line

If you want to read a file line by line, into an array, you can use this code:


package main

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

// read line by line into memory
// all file contents is stores in lines[]
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() {
  // open file for reading
  // read line by line
  lines, err := readLines("read2.go")
  if err != nil {
    log.Fatalf("readLines: %s", err)
  }
  // print file contents
  for i, line := range lines {
    fmt.Println(i, line)
  }
}

Exercises

  1. Think of when you’d read a file ‘line by line’ vs ‘at once’?
  2. Create a new file containing names and read it into an array

Download Answers