Skip to main content

Read File Line by Line using Golang

Reading a file is very common functionality of programming languages. The files read and write functionality implemented in web applications.

In our previous tutorial you have learned how to read Read CSV File using Golang. In this tutorial you will learn how to implement functionality to read file line by line using Golang. We will create a text file and read text file line by line to display data using Golang.

We will cover this tutorial step by step to create a Go file to implement functionality to read text file line by line and display file data.

The Go has bufio package to read files line by line. In this tutorial, we will use this package to read file line by line.

Also, read:

Step1: How to Read File in Golang

The Go programming language has bufio package to read the text by lines or words from a file. We will use bufio package to read the file. We will create Go file main.go and import necessary packages.

package main
 
import (
	"bufio"
	"fmt"
	"log"
	"os"
)

Step2: Read File Line By Line in Golang

Now we will create a text file text.txt and open file using os.Open() function and it returns pointer of type file. We will read file using bufio.NewScanner() and then read line by line with fileScanner.Split(bufio.ScanLines). Then we will loop through lines to append text into variable and finaly loop through to each lines to print each line data.

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)
	}
}

Step3: Complete Code to Read File Line by Line using Go

Here is complete code of go file main.go to read file data line by line. Just run this file to get desired output.

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)
	}
}

Step4: Run Read File Line by Line using Go Example

Now finally we will run our main.go file with above code using go run command to read file line by line and display data.

C:\golang>go run main.go

We will see the read text file data line by line as output on console.

You may also like: