Read a Text File in Golang is easy with scanner, we teach you how to do it.
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:
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:
We hope this example is useful for you.