How to read file line by line in Golang
In this article, you are going to learn about how to read file line by line in Golang.
Golang is an open-source programming language which is developed by Google. By using Golang you can do so many things, reading files line by line is one of them. To read a file in Golang, we will use bufio package scanner.
Let’s assume that, you have a test.txt file that contains some text. Here, In our case, we have a text.txt file that contains the following texts.
GO Language is an open-source statically compiled programming language. It was designed at Google by Rob Pike, Ken Thompson, and Robert Grieserner. It is also known as Golang. In this article we will learn about how to read line by line in Golang.
Now, we want to read this file line by line. To implement this in Golang follow the below code example:
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
readFile, err := os.Open("test.txt")
if err != nil {
log.Fatalf("failed to open file: %s", err)
}
fileScanner := bufio.NewScanner(readFile)
fileScanner.Split(bufio.ScanLines)
var fileTextLines []string
for fileScanner.Scan() {
fileTextLines = append(fileTextLines, fileScanner.Text())
}
readFile.Close()
for _, eachline := range fileTextLines {
fmt.Println(eachline)
}
}
Here, at first, we import our required packages, and then we read our test.txt file with the help of os.Open(). We also handled errors if there’s any unwanted situation occurred and finally, we implemented our functionality for reading the file line by line with the help of bufio package.
Output:
If you run the file, you will see following output in your terminal
You can see the exact same text that was consisted in our test.txt file. This is how you can read file line by line in Golang. Your directory name can be different from this.