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 (
	"bufio"
	"fmt"
	"log"
	"os"
)

//geekole.com

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

	defer file.Close()

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

You can use a text file like this:

Read Text File in Golang

First we create a module.

go mod init yourdomain.com/examples

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

go build

And finally, execute the binary file:

.\examples.exe

You will see every line in your text file:

Read Text File in Golang

We hope this example is useful for you.

Se more: https://decodigo.com/go-leer-archivo-de-texto