0Pricing
Go Academy · Lesson

Reading Files with os and bufio

Open, read lines, and close files safely

Reading Files with os and bufio is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

os.ReadFile

os.ReadFile (Go 1.16+) reads an entire file into a byte slice in one call. Simple and idiomatic for small files.

data, err := os.ReadFile("config.json")
if err != nil { log.Fatal(err) }
fmt.Println(string(data))

os.Open and manual close

For more control, open a file with os.Open (read-only) and close it with defer:

f, err := os.Open("data.txt")
if err != nil { return err }
defer f.Close()

Reading into a buffer

Read a chunk of bytes with f.Read(buf). It returns the number of bytes read and io.EOF when the file ends.

buf := make([]byte, 1024)
n, err := f.Read(buf)
if err != nil && err != io.EOF { return err }
fmt.Println(string(buf[:n]))

bufio.NewReader

Wrap a file in bufio.Reader to buffer reads, reducing syscalls. Methods include ReadString, ReadLine, and ReadByte.

reader := bufio.NewReader(f)
line, err := reader.ReadString('\n')

Reading line by line with bufio.Scanner

bufio.NewScanner is the idiomatic way to read a text file line by line. The default split function is ScanLines.

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

Custom scanner buffer

The default scanner buffer is 64 KiB. For files with very long lines, increase the buffer with scanner.Buffer.

buf := make([]byte, 1024*1024)
scanner.Buffer(buf, len(buf))

io.ReadAll

io.ReadAll reads from any io.Reader until EOF and returns the bytes. Useful for reading from network connections, response bodies, or files wrapped in readers.

data, err := io.ReadAll(f)

Scanning words and bytes

Replace the scanner's split function to scan words (bufio.ScanWords) or individual bytes (bufio.ScanBytes).

scanner.Split(bufio.ScanWords)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

Reading structured text

After reading lines, use strings.Fields or strings.Split to parse columns:

for scanner.Scan() {
    fields := strings.Fields(scanner.Text())
    // fields[0], fields[1], ...
}

File reading errors

Always check the scanner's Err() after the scan loop — it returns the first non-EOF error. A loop that finishes normally without scanning any lines may still have encountered an error.

Reading named stdin

Use os.Stdin anywhere an io.Reader is accepted. This makes CLI tools work with both file arguments and piped input.

scanner := bufio.NewScanner(os.Stdin)

Quick Check

Which bufio type is the idiomatic way to read a text file line by line in Go?

Recap: Reading Files

Key points:

  • os.ReadFile: entire small file in one call
  • bufio.Scanner: line-by-line reading; check Err() after loop
  • bufio.Reader: buffered reads reducing syscalls
  • io.ReadAll: read any io.Reader to completion

Frequently asked questions

Is the “Reading Files with os and bufio” lesson free?

Yes — the full text of “Reading Files with os and bufio” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Reading Files with os and bufio”?

Open, read lines, and close files safely You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Reading Files with os and bufio” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Files with os and bufio
  2. Writing Files and Temp Files
  3. JSON Encoding and Decoding
  4. Streaming JSON and CSV
← Back to Go Academy