GO GO

Reading a File Line by Line in Go: A Step Tracker That Survives a Messy Log

Dima Nov 17, 2026

Introduction

Reading a text file is one of the first useful things a program does, and Go makes the happy path short. The trouble is everything off the happy path. Go reports problems as ordinary values called errors, and a beginner's first instinct is to throw them away with _ to get the code running. The program then fails somewhere else entirely, with a message that has nothing to do with the real cause.

In this tutorial we will write a program that reads a week of daily step counts exported from a fitness tracker and prints a summary. We will start with a version that ignores every error and watch it panic for reasons it cannot explain. Then we will open the file properly, read it line by line with bufio.Scanner, turn text into numbers with strconv.Atoi, skip broken lines with a useful message, compute an average without integer division, and take the file name from the command line.

I will assume you are working in the Go sandbox on Bytestark, with the terminal in /home/coder/learning, which holds a Go module named learning. You should be able to run a Go program with go run, and know slices, for loops and if.


Background

In Go, a function that can fail returns an error as its last result. The type is called error, and the special value nil means "no error". The caller checks it immediately, with the pattern you will see many times below: if err != nil { ... }. Go has no exceptions; an error you do not check is simply ignored.

A few standard packages do the work in this tutorial:

  • os talks to the operating system. os.Open opens a file for reading, os.Exit ends the program with an exit code, os.Args holds the command-line arguments, and os.Stderr is the error output stream.
  • bufio provides buffered reading. A bufio.Scanner reads its input one line at a time.
  • strings works on text. strings.Fields splits a line into words wherever there is whitespace.
  • strconv converts between strings and numbers. strconv.Atoi turns text like "8432" into the int 8432, or returns an error if the text is not a number.

When a Go program hits a problem it cannot continue from, such as reading past the end of a slice, it panics: it stops and prints the reason and the line where it happened.


Practical Scenario

A small running club runs a monthly step challenge. Each member exports a text file from their fitness tracker, one line per day with the date and the number of steps, and the club's organiser runs a program on each file to get the total, the daily average, and how many days the member reached the 10,000-step goal.

The exports are not clean. A tracker that lost its sync writes a date with no number. A member who edited their file by hand typed a word where the number should be. And sometimes a member sends the wrong file name, or no file at all. The program must not crash on any of these, must not quietly count a bad line as a day with zero steps, which would drag the average down, and must say exactly which line it skipped and why.

We will work with one member's export for a week, and two of its seven lines are broken.


The Problem

Here is the first version, written to get a number on the screen as fast as possible. It reads the whole file, splits it into lines, takes the second word of each line as the step count, and adds them up. Every error is thrown away with _.

Create a folder and a file:

mkdir stepcount
touch stepcount/main.go


Put this in stepcount/main.go:

package main

import (
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    data, _ := os.ReadFile("steps.txt")
    lines := strings.Split(string(data), "\n")

    total := 0
    for _, line := range lines {
        fields := strings.Fields(line)
        steps, _ := strconv.Atoi(fields[1])
        total += steps
    }
    fmt.Println("total steps:", total)
}


Go into the folder and run it. We have not created the step file yet:

cd stepcount
go run .


panic: runtime error: index out of range [1] with length 0

goroutine 1 [running]:
main.main()
    /home/coder/learning/stepcount/main.go:17 +0x129
exit status 2


The program panicked, and the message is about slice indexes, not about files. Let's read it and then trace how a missing file turned into this.

  • panic: runtime error: index out of range [1] with length 0 says we asked for element [1] of a slice that has no elements.
  • main.main() and /home/coder/learning/stepcount/main.go:17 point at line 17, steps, _ := strconv.Atoi(fields[1]). The +0x129 is a position in the machine code and can be ignored.
  • exit status 2 is added by go run: a panic ends the program with code 2.

Now the trace. os.ReadFile("steps.txt") reads a whole file into memory and returns two values, the contents and an error. The file does not exist, so it returned empty contents and an error saying so, and _ threw the error away. strings.Split on an empty string returns a slice with one empty string in it, so the loop ran once with line equal to "". strings.Fields("") returns a slice with no words, and fields[1] asks for the second word of nothing. The real problem, a missing file, happened on line 11. The program noticed on line 17, and the message mentions neither files nor steps.txt.

That is the general cost of ignoring errors: the failure moves away from its cause and loses its explanation.


Opening the File and Checking the Error

The first fix is to open the file with os.Open, check its error right away, and stop with a clear message if it failed. At the same time we switch to reading the file one line at a time with a bufio.Scanner, which does not need to hold the whole file in memory. Replace the whole of main.go with:

package main

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

func main() {
    file, err := os.Open("steps.txt")
    if err != nil {
        fmt.Println("error:", err)
        os.Exit(1)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()
        fmt.Println("read:", line)
    }
}


Run it, still without a step file:

go run .


error: open steps.txt: no such file or directory
exit status 1


This time the message names the operation, the file and the reason. err is the error that os.Open returned. Printing an error prints its message, and the message from os.Open already says everything: open steps.txt: no such file or directory. os.Exit(1) ends the program immediately with exit code 1, which tells any script running it that it failed. go run reports that code as exit status 1.

Now create the export in the stepcount folder:

touch steps.txt


Put this in steps.txt:

2026-11-10 8432
2026-11-11 10250
2026-11-12 6120
2026-11-13 twelve
2026-11-14 11873
2026-11-15
2026-11-16 9050


Run the program again:

go run .


read: 2026-11-10 8432
read: 2026-11-11 10250
read: 2026-11-12 6120
read: 2026-11-13 twelve
read: 2026-11-14 11873
read: 2026-11-15
read: 2026-11-16 9050


Every line of the file comes through. Let's go through the new code.

  • file, err := os.Open("steps.txt") opens the file for reading. On success, file is a handle to the open file and err is nil. On failure, file is not usable, which is why nothing touches it before the check.
  • defer file.Close() schedules file.Close() to run when main returns, however it returns. An open file holds a resource from the operating system, and closing it gives that back. Writing the close right after the successful open, with defer, means you cannot forget it later, even if the function grows several return statements.
  • scanner := bufio.NewScanner(file) creates a scanner that reads from the file.
  • for scanner.Scan() is the reading loop. Each call to Scan reads the next line and returns true, or returns false when there are no more lines, which ends the loop. This is a for with only a condition, Go's way of writing what other languages call a while loop.
  • scanner.Text() returns the line just read, as a string, without its newline character.

Try it: Put the first version of main.go back, the one with os.ReadFile and the _s, and run it now that steps.txt exists. Predict whether it works. It panics again, index out of range [1] with length 1 on line 17, this time on the line 2026-11-15, which has a date and no number. The file is fine now, but the next ignored problem is waiting. Restore the os.Open version.


Turning Lines Into Numbers, and Skipping Bad Ones

Next we split each line into its date and step count, convert the count to a number and add it up. Here is the version most people write first, with the conversion's error ignored. Replace the whole of main.go with:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    file, err := os.Open("steps.txt")
    if err != nil {
        fmt.Println("error:", err)
        os.Exit(1)
    }
    defer file.Close()

    total := 0
    days := 0
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fields := strings.Fields(scanner.Text())
        steps, _ := strconv.Atoi(fields[1])
        total += steps
        days++
    }
    fmt.Println("days:", days, "total steps:", total)
}


go run .


panic: runtime error: index out of range [1] with length 1

goroutine 1 [running]:
main.main()
    /home/coder/learning/stepcount/main.go:24 +0x285
exit status 2


The same panic as in the Try it above, now on line 24. The line 2026-11-15 splits into one word, the date, and fields[1] asks for a second word that is not there. Indexing a slice beyond its length always panics in Go; it never returns a made-up value.

Every line has to be checked before we use it, and every conversion has to be checked after we make it. Replace the part of main from total := 0 down to the end of the for loop with:

    total := 0
    days := 0
    lineNumber := 0
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        lineNumber++
        fields := strings.Fields(scanner.Text())
        if len(fields) != 2 {
            fmt.Fprintf(os.Stderr, "line %d: expected a date and a step count\n", lineNumber)
            continue
        }
        steps, err := strconv.Atoi(fields[1])
        if err != nil {
            fmt.Fprintf(os.Stderr, "line %d: %v\n", lineNumber, err)
            continue
        }
        total += steps
        days++
    }


Build it and run it:

go build && ./stepcount


line 4: strconv.Atoi: parsing "twelve": invalid syntax
line 6: expected a date and a step count
days: 5 total steps: 45725


The two broken lines are reported with their line numbers and left out, and the five good days add up to 45,725 steps. Let's look at the checks.

  • lineNumber counts lines as they are read, so messages can say where the problem is. It starts at 0 and is increased at the top of the loop, so the first line is line 1, the way people count lines.
  • if len(fields) != 2 makes sure there is exactly a date and a count before we index the slice. That one check prevents the panic, and it also catches a line with extra words.
  • steps, err := strconv.Atoi(fields[1]) keeps the error this time. For "twelve", Atoi returns 0 and an error whose message is strconv.Atoi: parsing "twelve": invalid syntax: the function name, the text it was given, and why it failed.
  • fmt.Fprintf(os.Stderr, ...) writes the warning to the standard error stream rather than standard output. In a terminal both appear on the screen, but they are separate streams, so the summary can be saved or piped somewhere while the warnings still reach the person running the program. %v is the general-purpose verb, which prints an error as its message.
  • continue skips the rest of the loop for this line, so it is neither added nor counted as a day.

You can see the two streams separate. 2>/dev/null sends standard error, stream number 2, to /dev/null, a special file that discards everything:

./stepcount 2>/dev/null


days: 5 total steps: 45725


Only the summary is left, because it went to standard output.

Try it: Go back to ignoring the conversion error: replace the four lines that start with steps, err := strconv.Atoi(fields[1]) with steps, _ := strconv.Atoi(fields[1]) and run it. Predict the summary line. It is days: 6 total steps: 45725. The twelve line no longer causes a warning; Atoi returned 0 for it, which added nothing to the total but counted as a sixth day. Every average computed from this would be too low, and nothing on the screen says why. Restore the error check.


Averages Without Integer Division

The club wants three numbers: total steps, the daily average, and how many days reached 10,000 steps. The average is where Go's integer arithmetic matters. Replace the whole of main.go with this version:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    file, err := os.Open("steps.txt")
    if err != nil {
        fmt.Println("error:", err)
        os.Exit(1)
    }
    defer file.Close()

    const goal = 10000
    total := 0
    days := 0
    goalDays := 0
    lineNumber := 0
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        lineNumber++
        fields := strings.Fields(scanner.Text())
        if len(fields) != 2 {
            fmt.Fprintf(os.Stderr, "line %d: expected a date and a step count\n", lineNumber)
            continue
        }
        steps, err := strconv.Atoi(fields[1])
        if err != nil {
            fmt.Fprintf(os.Stderr, "line %d: %v\n", lineNumber, err)
            continue
        }
        total += steps
        days++
        if steps >= goal {
            goalDays++
        }
    }

    average := float64(total) / float64(days)
    fmt.Printf("days counted: %d\n", days)
    fmt.Printf("total steps:  %d\n", total)
    fmt.Printf("average:      %.0f per day\n", average)
    fmt.Printf("goal reached: %d of %d days\n", goalDays, days)
}


go build && ./stepcount 2>/dev/null


days counted: 5
total steps:  45725
average:      9145 per day
goal reached: 2 of 5 days


Five valid days, an average of 9,145 steps, and two days over the goal: the 11th with 10,250 and the 14th with 11,873. Here is what changed.

  • const goal = 10000 names the target, so the comparison reads as what it means.
  • goalDays counts the days that reached it, increased inside the loop by if steps >= goal. It sits after the error checks, so a broken line can never count as a goal day.
  • average := float64(total) / float64(days) converts both counts to float64 before dividing. In Go, dividing two int values throws away the fraction, so total / days would be integer division. Go also refuses to divide a float64 by an int, so both sides must be converted. Here 45725 / 5 happens to be exactly 9145, but with other data the fraction would matter.
  • %.0f prints a float64 rounded to no decimal places, since half a step is not useful information.

Try it: Change the average line to average := total / days and run go run . 2>/dev/null. Predict the average line. It compiles, since average simply becomes an int, but it prints average: %!f(int=9145) per day: the verb %.0f expects a float64, and fmt reports the mismatch inside the output. go vet . would flag that line before you ran it. Put the conversion back.


Choosing the File From the Command Line

The organiser has a file for every member, and the program can only read steps.txt. The file name should be given when the program is run, as in ./stepcount steps.txt. Command-line arguments are in os.Args, a slice of strings. os.Args[0] is the program's own name, and the arguments typed after it start at os.Args[1].

Replace the beginning of main, up to and including the error check after os.Open, with:

func main() {
    if len(os.Args) != 2 {
        fmt.Fprintln(os.Stderr, "usage: stepcount FILE")
        os.Exit(2)
    }

    file, err := os.Open(os.Args[1])
    if err != nil {
        fmt.Fprintln(os.Stderr, "error:", err)
        os.Exit(1)
    }


Build it and run it three ways, with no file, with a file that does not exist, and with the export:

go build && ./stepcount; echo $?


usage: stepcount FILE
2


./stepcount monday.txt; echo $?


error: open monday.txt: no such file or directory
1


./stepcount steps.txt 2>/dev/null; echo $?


days counted: 5
total steps:  45725
average:      9145 per day
goal reached: 2 of 5 days
0


echo $? prints the exit code of the previous command, and each case ends with a different one: 2 for "called incorrectly", 1 for "could not read the file", 0 for success. Scripts that process every member's file can tell these apart without reading the messages.

if len(os.Args) != 2 checks that exactly one argument was given, the program name plus one file name. Without this check, os.Args[1] on a bare ./stepcount would be the same out-of-range panic we started with. The usage message is the conventional one-line reminder of how to call a program, and like every other message about a problem, it goes to os.Stderr, now with fmt.Fprintln. os.Open(os.Args[1]) opens whatever file was named.

With go run, arguments for the program go after the package: go run . steps.txt.

Try it: Create an empty file with touch empty.txt and run ./stepcount empty.txt. Predict the average line before you look. It prints average: NaN per day, with days counted: 0. Floating-point division of 0 by 0 does not panic; it produces the special value NaN, "not a number". Integer division by zero would have panicked instead. A real tool would check days == 0 before dividing and print a clear message.


Summary

We built a summary tool for a step challenge that reports a missing file clearly, skips broken lines with their line numbers, computes an honest average, and reads whichever file it is given. We kept the format to one date and one number per line. Parsing the dates, validating that they are in order, or reading CSV with the encoding/csv package are natural next steps.

  • Ignoring an error with _ does not make the failure go away; it moves it to a later line and strips it of its explanation.
  • Check every error immediately with if err != nil, and stop or skip with a message that names the file or line involved.
  • Open files with os.Open, and put defer file.Close() on the line right after the successful error check, so the file is closed however the function returns.
  • Read line by line with scanner := bufio.NewScanner(file) and for scanner.Scan() { line := scanner.Text() }.
  • Indexing a slice past its length always panics; check len before reading fields[1].
  • strconv.Atoi returns 0 and an error for text that is not a number; keeping the error is the only way to tell a bad line from a real zero.
  • Send warnings and usage messages to os.Stderr with fmt.Fprintf or fmt.Fprintln, so that results on standard output can be redirected separately.
  • Convert both operands to float64 before dividing for an average; floating-point division by zero gives NaN rather than a panic.
  • os.Args[0] is the program name and the arguments start at os.Args[1]; check len(os.Args) first and exit with distinct codes for different failures.

You need to be logged in to access the cloud lab.

Log in