Go program to reading plain text files
The bufio package
Scanner
generally used for reading the text by lines or words from a file. The following source code snippet shows reading text line-by-line from the plain text file as below.
Example
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
file.Close()
for _, eachline := range txtlines {
fmt.Println(eachline)
}
}
Output
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nunc a mi dapibus, faucibus mauris eu, fermentum ligula.
Donec in mauris ut justo eleifend dapibus.
Donec eu erat sit amet velit auctor tempus id eget mauris.
The program after execution shows the below output line-by-line as they read it from the file.