How to Read a File Line by Line to String in Golang?
Last Updated :
22 Jun, 2020
To read a file line by line the bufio package Scanner is used. Let the text file be named as sample.txt and the content inside the file is as follows:
GO Language is a statically compiled programming language, It is an open-source language. It was designed at Google by Rob Pike, Ken Thompson, and Robert Grieserner. It is also known as Golang. Go language is a general-purpose programming language mainly meant for building large scale complex software.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open( "sample.txt" )
if err != nil {
log .Fatalf( "failed to open" )
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var text []string
for scanner.Scan() {
text = append(text, scanner.Text())
}
file.Close()
for _, each_ln := range text {
fmt.Println(each_ln)
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...