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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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