Golang program to read the content of a file line by line


In golang there are various internal packages such as bufio, os and io that can be used for reading the content of a file line by line. The bufio and os packages are used for opening and scanning the file using os.open and bufio.NewScanner function. The io package we are going to use ioutil.ReadFile to read the file from the given destination and the use the string function to display it in the output.

Method 1: Using bufio and os package

In this illustration, bufio.NewScanner is used to read line by line content and os.Open is used to open the file. As long as there is a line to read and a scanner, the scan method returns true. The currently read line is returned by text. When the function returns, the file will be closed using the defer statement.

Syntax

os.Open

This function is a part of os package. It is used to open a file to read. It takes one input i.e. the filename which will be opened.

bufio.NewScanner

This function is a part of the bufio package. It is used to create a scanner object to read the data from the file.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), bufio and os package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Create a main function and in that function open the file whose content is to be read using os.Open function from os package.

  • Step 3 − If an error comes while opening the file print the error on the console and return.

  • Step 4 − Close the opened file using defer keyword and close function.

  • Step 5 − Create a bufio.NewScanner object with the file as an argument inside it and read the contents line by line by iterating through the lines of file.

  • Step 6 − The condition used in iteration will be until there is a line present in the file read it and print otherwise terminate the loop using scanner.Scan() function.

  • Step 7 − But if there is an error while scanning print the error on the console using fmt.Println()

Example

In this example, we will use scanner to read the contents of a file line by line.

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

func main() {
	myfile, err := os.Open("file1.txt")  //open the file
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer myfile.Close()

	scanner := bufio.NewScanner(myfile)  //scan the contents of a file and print line by line
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Println(line)
	}

	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading from file:", err) //print error if scanning is not done properly
	}
}

Output

line 1
line 2
line 3

Method 2: Using io/ioutil and strings package

This instance uses ioutil.ReadFile to read the contents of file into memory as []bytes using the function. The string function and the strings are then used to turn the contents into a string. The string is divided into a number of lines, each separated by a newline character, using the Split function. Following that, the for loop prints each line after iterating through the lines.

Syntax

Ioutil.ReadFile

This function is available in the ioutil package and is used to read the contents of a file with filename as an input in the function

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), io/ioutil and strings package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Create a main function and in that function read the file file1.txt using ioutil.ReadFile function.

  • Step 3 − If an error comes while reading the file print the error and return.

  • Step 4 − Use strings.Split function to split the data using \n.

  • Step 5 − Iterate the string that has been split, print the content line by line.

  • Step 6 − The print statement is executed using fmt.Println() function where ln means new line.

Example

In this example we will use ioutil.ReadFile function from io package.

package main
import (
   "fmt"
   "io/ioutil"
   "strings"
)

func main() {
   data, err := ioutil.ReadFile("file1.txt")  //read the file 
   if err != nil {
      fmt.Println("Error reading file:", err) //print the error if comes while reading file 
      return
   }
   read_lines := strings.Split(string(data), "\n")
   for _, line := range read_lines {
      fmt.Println(line) //print the content line by line
   }
}

Output

line 1
line 2
line 3

Conclusion

We executed the program of reading the content of a file line by line using two examples. In the first example bufio and os package will be used and in the second example io/ioutil package will be used.

Updated on: 22-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements