Read a Whole File into Memory in Go with os.ReadFile
Read an entire file with os.ReadFile, which returns bytes and an error, and test the error with errors.Is(err, fs.ErrNotExist). It replaces ioutil.ReadFile from Go 1.16.
A Go program needs the complete contents of a small file in one call.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func main() {
os.WriteFile("hello.txt", []byte("hello\nworld\n"), 0o644)
data, err := os.ReadFile("hello.txt")
fmt.Printf("%q %v\n", data, err)
_, err = os.ReadFile("missing.txt")
fmt.Println(err)
fmt.Println("not exist:", errors.Is(err, fs.ErrNotExist))
_, err = os.ReadFile("/tmp")
fmt.Println(err)
}"hello\nworld\n" <nil>
open missing.txt: no such file or directory
not exist: true
read /tmp: is a directoryos.ReadFile(name) opens the file, reads to the end and closes it, returning []byte. The errors keep the operation and the path, as in open missing.txt: no such file or directory, and they wrap the underlying error, so errors.Is(err, fs.ErrNotExist) is true for a missing file. Reading a directory fails with is a directory. See os.ReadFile.
The whole file is held in memory, so use bufio.Scanner or io.Copy for large files or when you can process a line at a time. ioutil.ReadFile still works but is deprecated. The run shows %q output because file contents are bytes and may hold anything. This was run with Go 1.19.