By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
os.ReadFile is convenient and wrong for a multi-gigabyte log. The io package models everything as a reader or writer, and the rest of the standard library composes with it: bufio buffers, csv parses, gzip decompresses, io.Copy moves bytes with a fixed buffer. Switching from a file to an HTTP body or a test string is then a one-line change because the code depends on io.Reader, not *os.File.
Two file details cause real incidents. Close every handle (defer it next to os.Open) and check the error from Close when you write, because buffered writes can fail at close time. When replacing a file atomically, write to a temporary file in the same directory and rename it over the target — a crash then leaves either the old file or the new one, never half of each.
encoding/csv handles quoting, embedded commas, embedded newlines and CRLF. Configure FieldsPerRecord to catch malformed rows and set ReuseRecord only when you copy the record before the next Read. For reports, stream rows to the client as you generate them instead of building a giant slice.
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
)
const data = `service,status
api,200
worker,500
`
func main() {
dir, err := os.MkdirTemp("", "relay-csv-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := dir + "/events.csv"
if err := os.WriteFile(path, []byte(data), 0o600); err != nil {
panic(err)
}
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = 2
rows := 0
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
if rows > 0 {
fmt.Println(record[0], record[1])
}
rows++
}
fmt.Println("rows", rows-1)
}| Tool | Use it for | Limit or gotcha |
|---|---|---|
io.Reader / io.Writer | Any streamed data | No seeking or size assumptions |
bufio.Scanner | Line-oriented text | 64 KiB token limit unless raised |
bufio.Reader | Lines of any length | Manage the buffer explicitly |
encoding/csv | Real CSV files | Quoting rules are not comma-splitting |
os.File | Local persistence | Close it; writes fail at close too |
io.Copy | Efficient pass-through | Wrap with a limiter if needed |
Key takeaways
Model file and network data as io.Reader/io.Writer so code composes and tests with strings.
Stream large files; avoid os.ReadFile for data that may exceed memory.
Defer Close next to Open and check write-close errors.
Use encoding/csv instead of splitting on commas, and set FieldsPerRecord.
Replace files atomically with a temporary file plus rename.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.