Go core
Browse topics

Reading and writing files

Version
1.27
Review
Draft

Summary#

os.ReadFile and os.WriteFile handle a whole file in one call. Use os.Open to read a file as a stream, or os.OpenFile with flags when you need another mode such as appending.

Syntax#

go
data, err := os.ReadFile(path)
err = os.WriteFile(path, data, 0o600)
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)

Example#

go
package main

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

func run() (err error) {
	dir, err := os.MkdirTemp("", "notes-*")
	if err != nil {
		return err
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "notes.txt")

	if err := os.WriteFile(path, []byte("alpha\n"), 0o600); err != nil {
		return err
	}

	file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
	if err != nil {
		return err
	}
	_, writeErr := file.WriteString("beta\n")
	if closeErr := file.Close(); writeErr != nil {
		return writeErr
	} else if closeErr != nil {
		return closeErr
	}

	data, err := os.ReadFile(path)
	if err != nil {
		return err
	}
	fmt.Printf("%d bytes: %q\n", len(data), data)
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Println(err)
	}
}

Expected output#

Text
11 bytes: "alpha\nbeta\n"

Common mistakes#

os.WriteFile truncates an existing file and keeps its permissions. For a new file the umask can remove permission bits from the requested mode. A failure partway through can leave partial content. os.OpenFile with O_APPEND|O_WRONLY requires an existing file. Add O_CREATE and a mode to create one if needed. Check the error from Close after writing, since a deferred Close alone discards it.

Version applicability#

os.Open and os.OpenFile work from Go 1.0. The 0o600 spelling requires Go 1.13. Go 1.16 added os.ReadFile, os.WriteFile and os.MkdirTemp, so the complete example requires Go 1.16 or later. Earlier versions use io/ioutil for the whole-file operations.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0