Read Text File in Golang

Read a Text File in Golang is easy with scanner, we teach you how to do it.

ยป More Golang Examples

The code:

package main

import (


func main() {
	file, err := os.Open("C:/Users/geekole/files/filename.txt")
	if err != nil {

	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {

You can use a text file like this:

Read Text File in Golang

First we create a module.

go mod init

To build our program and binary file we use this command:

go build

And finally, execute the binary file:


You will see every line in your text file:

Read Text File in Golang

We hope this example is useful for you.

Se more: