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.
Most Helpful This Week
Program in Go language to print Floyd's Triangle
Golang read csv file into struct
GO Program to Find Factorial of a Number
How to set timeout for http.Get() requests in Golang?
Type assertion in Go Programming Language
Golang writing struct to JSON file
Golang program for implementation of Longest Common Sub-sequence
Declaration of a struct type
Web Application to Get Trending Hashtags Near a Location
This sample program demonstrates how to decode a JSON string.