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)
}
}
Reading a file line by line in Go processes one line at a time instead of loading the whole file into memory at once. It is the standard way to handle text files in Go because it manages large files without crashing your computer. Think of it like reading a book one page at a time rather than trying to hold the entire book in your hands simultaneously.