Go 1.27 reference · Files, HTTP and Logging

Go os.ReadFile and os.WriteFile Function

Read or write a whole file in one call, with Unix permissions for new files; errors wrap fs.ErrNotExist and friends.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func ReadFile(name string) ([]byte, error)   func WriteFile(name string, data []byte, perm FileMode) error

Parameters

ParameterDescription
perm Permissions for new files, e.g. 0o644.
os.Create / os.Open For streaming reads and writes.
errors.Is(err, fs.ErrNotExist) Check for a missing file.

Examples

Example 1
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	dir, _ := os.MkdirTemp("", "demo")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "notes.txt")
	if err := os.WriteFile(path, []byte("buy tea\n"), 0o644); err != nil {
		panic(err)
	}
	data, _ := os.ReadFile(path)
	fmt.Print(string(data))
}

Output

buy tea

Run this on your computer — see “Get Started” for setup.

A missing file
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
)

func main() {
	_, err := os.ReadFile("does-not-exist.txt")
	fmt.Println(errors.Is(err, fs.ErrNotExist))
}

Output

true

Run this on your computer — see “Get Started” for setup.

Was this page helpful?