How to Read a File Line by Line in Go

Read a file line by line in Go using bufio.Scanner to process text efficiently without loading the entire file into memory.

Use bufio.Scanner to read a file line by line efficiently.

package main

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

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

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
}