Golang: Read data from file line by line

Reading data from files is a common use case. Most of the time you need to read data line by line.

There are multiple ways to read data from the file.  

The simplest way is to open a file and use a scanner to read data line by line. The sample code below does the same. 

package main

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

func main() {
	readLineByLine("file_path")
}

func readLineByLine(filePath string) {
	f, err := os.Open(filePath)       //Open file for reading
	if err != nil {
		fmt.Println("Unable to open the file. Error: ", err)
		return
	}
    defer f.Close()     //Close file pointer after reading file.
    
    line := bufio.NewScanner(f)    //Scanner to read line by line
	for line.Scan() {
		fmt.Println(line.Text())
	}
}
Other related posts: 

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...