How to Read a File Line by Line in Golang

To read a file line by line in Golang, you can use the bufio.NewScanner() to create a scanner and then use the .Text() method. The bufio package provides a convenient Scanner type that reads a file line by line.

Syntax

scanner = bufio.NewScanner()

line = scanner.Text()

Example 1

Create a data.txt file and add the following lines to it.

This is a text file
The file is read line by line
Hello World

Save this file in your current working directory where the .go file is there.

Now, you can use the data.txt file inside the .go file and read a file line by line.

package main

import (
  "bufio"
  "fmt"
  "os"
)

func main() {
  file, err := os.Open("data.txt")
  if err != nil {
    fmt.Println(err)
  }
  defer file.Close()

  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    fmt.Println(scanner.Text())
  }

  if err := scanner.Err(); err != nil {
   fmt.Println(err)
  }
}

Output

This is a text file
The file is read line by line
Hello World

In this example, we opened the file using the os.Open() method and handle any errors that may occur.

We then created a scanner using the bufio.NewScanner() and loop through each line using the scanner.Scan() method.

Inside the loop, we get the current line using the scanner.Text(). Finally, we checked for any errors during scanning using a scanner.Err().

The scanner will throw an error with lines longer than 65536 characters. If your line length exceeds 64K, you can use the Buffer() method to increase the scanner’s capacity.

Example 2

package main

import (
  "bufio"
  "fmt"
  "os"
)

func main() {
  file, err := os.Open("data.txt")
  if err != nil {
    fmt.Println(err)
  }
  defer file.Close()

  scanner := bufio.NewScanner(file)
  scanner.Split(bufio.ScanLines)

  for scanner.Scan() {
    line := scanner.Text()
    fmt.Println(line)
  }

  if err := scanner.Err(); err != nil {
    fmt.Println(err)
  }
}

Output

This is a text file
The file is read line by line
Hello World

In this example, the os.Open() function opens a file.

In the next step, the bufio.NewScanner() function created the file scanner.

The bufio.ScanLines() function is used with the scanner to split the file into lines.

Then, the scanner Scan() function is used in a loop to read each file line, and the Text() function is used to get the text of the current line.

At last, we printed the line using the fmt.Println() function.

That’s it.

Leave a Comment