Go Read File Line By Line

6 min read

Reading a file line by line in Go is one of the most common tasks you will encounter when working with logs, configuration files, CSV data, or any text-based format. The phrase "go read file line by line" points to a fundamental skill: instead of loading an entire file into memory at once, you process it one line at a time for better performance and lower memory usage. This guide walks you through the standard approaches, explains the underlying mechanics, and highlights the pitfalls that trip up both beginners and experienced developers Worth keeping that in mind. Took long enough..

Why Read a File Line by Line?

When you handle large files, loading everything into memory with something like os.ReadFile can quickly exhaust available RAM. Imagine reading a 2 GB server log. Attempting to hold the whole thing in a single string slice is wasteful and often impossible on modest hardware Worth keeping that in mind. Took long enough..

Reading a file line by line solves this problem elegantly. The program keeps only the current line in memory, processes it, and moves on. This streaming approach gives you:

  • Constant memory usage regardless of file size.
  • The ability to stop early once you find what you need.
  • Real-time processing, such as handling each line as it arrives in a live log.

These benefits make line-by-line reading the idiomatic way to work with text in Go.

The Standard Tool: bufio.Scanner

The most popular and recommended method to read a file line by line in Go uses the bufio.Scanner. A scanner splits input into tokens, and by default it splits on lines using the ScanLines function.

Here is the canonical example:

package main

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

func main() {
    file, err := os.txt")
    if err != nil {
        log.Consider this: open("data. Fatal(err)
    }
    defer file.

    scanner := bufio.Plus, newScanner(file)
    for scanner. Worth adding: scan() {
        line := scanner. Text()
        fmt.

    if err := scanner.Worth adding: err(); err ! = nil {
        log.

Let us break down what is happening:

1. **`os.Open`** opens the file and returns a pointer plus an error. Always check the error first.
2. **`defer file.Close()`** guarantees the file descriptor is released when the function returns.
3. **`bufio.NewScanner`** wraps the file in a scanner.
4. **`scanner.Scan()`** advances to the next line and returns `true` while lines remain.
5. **`scanner.Text()`** retrieves the current line as a string.
6. **`scanner.Err()`** reports any error that stopped scanning, other than a normal end-of-file.

Notice how clean this is. The scanner handles the low-level buffering for you, and the loop reads naturally from top to bottom.

## A Common Pitfall: The Scanner Buffer Limit

The biggest gotcha with `bufio.Scanner` is its default maximum token size. The scanner uses an internal buffer that starts small and grows, but it caps out at **64 KB (65536 bytes)** per line by default. If any single line exceeds this limit, `Scan()` returns `false` and `scanner.Err()` reports the error `bufio.Scanner: token too long`.

To handle longer lines, increase the buffer with the `Buffer` method:

```go
scanner := bufio.NewScanner(file)
maxCapacity := 10 * 1024 * 1024 // 10 MB
buf := make([]byte, 64*1024, maxCapacity)
scanner.Buffer(buf, maxCapacity)

for scanner.Scan() {
    fmt.Println(scanner.Text())
}

The Buffer method takes two arguments: the initial buffer slice and the maximum size it may grow to. Setting a generous maximum prevents the "token too long" error on files with very long lines, such as minified JSON or wide CSV records.

Not the most exciting part, but easily the most useful.

The Alternative: bufio.Reader with ReadString

If you need more control, the bufio.Reader type offers the ReadString method, which reads until a delimiter such as a newline character:

package main

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

func main() {
    file, err := os.On top of that, open("data. txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.

    reader := bufio.= nil {
            if err == io.Fatal(err)
        }
        fmt.= "" {
                    // process the final line without a trailing newline
                    fmt.EOF {
                if line !But newReader(file)
    for {
        line, err := reader. Which means trimSpace(line))
                }
                break
            }
            log. Still, readString('\n')
        if err ! Println(strings.Println(strings.

There is an important detail here. That's why when `ReadString` reaches the end of the file without finding the delimiter, it returns the data read so far along with `io. So eOF`. You must handle that final line explicitly, otherwise the last line of a file that lacks a trailing newline gets dropped.

### Choosing Between Scanner and Reader

Use `bufio.Which means reach for `bufio. Scanner` when you want the simplest, most readable code for typical line-by-line parsing. Reader` when you need to customize the delimiter, read fixed-size chunks, or handle unusual encoding boundaries with finer control.

## Reading Line by Line Concurrently

For CPU-bound work on each line, you may want to parallelize processing. A common pattern combines a scanner with goroutines and a worker pool:

```go
lines := make(chan string)
var wg sync.WaitGroup

// start workers
for i := 0; i < runtime.NumCPU(); i++ {
    wg.Add(1)
    go func() {
        defer wg.

}
        }
    }()
}

file, err := os.Open("data.Day to day, txt")
if err ! In practice, = nil {
    log. Fatal(err)
}
defer file.

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    lines <- scanner.Text()
}
close(lines) // signal workers that no more lines are coming
wg.

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

A few things make this pattern safe. The channel `lines` is unbuffered, so each worker pulls a line only when it is ready, which provides natural backpressure and keeps memory bounded even for multi-gigabyte files. Closing the channel is what terminates the workers: a `range` over a channel exits once it is closed and drained. Finally, `wg.Wait()` blocks `main` until every worker has finished, so the program does not exit before processing completes.

The scanner runs in the main goroutine while the workers consume in parallel, so parsing and processing overlap. This keeps I/O sequential and predictable while spreading the CPU-bound work across cores. Day to day, remember that `bufio. Scanner` is not safe for concurrent use, which is exactly why the pattern above sends plain strings over a channel rather than sharing the scanner itself.

And yeah — that's actually more nuanced than it sounds.

## A Note on Error Handling and Resource Cleanup

Two habits pay off in production code. First, always check `scanner.Err()` after the loop. `Scan()` returning `false` means either the file ended or an error occurred, and only `Err()` distinguishes the two. Silently ignoring it turns a read failure into what looks like a successfully processed, truncated file.

Second, close files with `defer file.Now, close()` immediately after a successful open. Deferred calls run in last-in, first-out order at function return, which is ideal for cleanup. If you process many files in a loop, though, be aware that deferred closes accumulate until the enclosing function returns; in that case close each file explicitly or wrap the per-file logic in its own function.

## Conclusion

Reading a file line by line in Go comes down to a small set of reliable tools. Worth adding: when you need a custom delimiter or explicit control over the end-of-file boundary, `bufio. Reader` with `ReadString` steps in, provided you handle the trailing line it returns alongside `io.Scanner` with its default `Scan()` loop handles the common case in just a few lines, and raising its buffer limit with `Buffer` covers unusually long lines. Also, eOF`. `bufio.For heavier workloads, feeding scanned lines into a worker pool lets you parallelize processing while keeping memory bounded through channel backpressure.

Whichever approach you choose, the same principles apply: check the error after the loop, close your files, and pick the tool whose trade-offs match the task. Master these few patterns and line-by-line file processing becomes one of the least surprising parts of your Go programs.
What's New

Just Shared

Related Corners

A Few More for You

Thank you for reading about Go Read File Line By Line. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home