Go - read file line by line

In this example, we will show you how to read a file line by line in Go with an example.

The Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text. It reads data by tokens; the Split function defines the token. By default, the function breaks the data into lines with line termination stripped.

Go - read file line by line

The example reads the file line by line. Each line is printed.

Let's create a 'sample.txt' file and add the following content to it:

My first fav programming languge is Go Lang
My second fav programming languge is Java
My third fav programming languge is Python

Let's create a file named go_example.go and add the following content to it:


package main

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

func main() {

    f, err := os.Open("thermopylae.txt")

    if err != nil {
        log.Fatal(err)
    }

    defer f.Close()

    scanner := bufio.NewScanner(f)

    for scanner.Scan() {

        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

Output:

G:\GoLang\examples>go run go_example.go
My first fav programming languge is Go Lang
My second fav programming languge is Java
My third fav programming languge is Python