Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Create a new file named main.go with the following code:

package main

func main() {

}

Create a text file named sample.txt with whatever text you want:

If opportunity doesn't knock, build a door.
This is a text file. There are many like it, but this one is mine...
This is a third line
This is a fourth

Next, we’ll open that file.

Next add the following to open up the file:

file, err := os.Open("sample.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

This line specifies that osOpen opens the file you pass to it (sample.txt)

It will return the file, or an error. If the error exists, it will run below and throw a fatal error with the error it found.

Then we defer the file closing, so when the application is finished the file closes.

Next, we’ll read the file:

Next we’ll use a Bufio scanner to read the file line by line:

scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}

Here we open a new bufio scanner and pass the file into it. It’s represented by the scanner variable.

Next the Scan() method advances the Scanner to the next token, which will run into a loop until all lines in the file are read.

fmt.Println then outputs the result of each line.

If the scanner returns an error, it will caught here and displayed:

if err := scanner.Err(); err != nil {
	log.Fatal(err)
}

The complete main.go should look like this:

package main

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

func main() {
	file, err := os.Open("sample.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
}

Next, lets run it!

You can now run the file. There’s two ways:

go run main.go

Or you can build it and run it:

go build main.go
./main

You will see the text as output!

“How to read a text file in Go”

Congrats! You did it?

Questions or comments? Reach out to me

Check out some of my Go Programming livestreams here.