Files and IO in Go
Read and write files with the os package, work with io.Reader and io.Writer, and use bufio for line reading and fast output.
Almost every Go program reads or writes something. This section covers the os, io and bufio packages, which handle files, streams and buffered input and output.
Reading and Writing Files
data, err := os.ReadFile("config.json")
if errors.Is(err, fs.ErrNotExist) {
// use defaults
}
os.ReadFile and os.WriteFile for small files, os.Open and os.OpenFile for streaming and appending.
io.Reader and io.Writer
Two one-method interfaces that files, buffers and network streams all share. Use io.Copy to move data and io.MultiWriter, io.TeeReader and io.LimitReader to combine streams.
Buffered IO with bufio
bufio.Scanner reads lines, s.Buffer fixes "token too long", and bufio.Writer speeds up output as long as you Flush.
Close what you open:
Every *os.File holds an operating system handle. Close it right after checking the open error, or long running programs run out of handles.
Summary
Use os to open files, accept io.Reader and io.Writer in your own functions, and reach for bufio when you read lines or write a lot.
Reading and Writing Files in Go
Read and write files in Go with os.ReadFile, os.WriteFile, os.Open and os.Create, handle missing files, append, and close files correctly.
io.Reader and io.Writer in Go
What io.Reader and io.Writer are, why so many Go APIs accept them, and how to compose them with io.Copy, io.MultiWriter, io.TeeReader and io.LimitReader.
Buffered IO with bufio in Go
Read lines with bufio.Scanner, fix the token too long error, read user input, and speed up writes with bufio.Writer and Flush.