os

os temporary-file I/O, WriteFile and ReadFile, and portable error checks with errors.Is rather than environment or home paths.

模块页正文目前为英文。

The os package provides operating-system functions, including file I/O. Import it as "os". The examples on this page create a directory with MkdirTemp, use files only inside it, and remove it afterward. They do not read environment variables, the home directory, or any other user file.

Permission bits are applied before umask. The 0o644 mode observed after WriteFile was measured on this darwin/arm64 host. Official documentation says that on Windows, Chmod and similar permission updates use only the 0o200 owner-writable bit to set or clear the read-only attribute; that Windows behavior is not measured here. Portable error handling uses errors.Is with os.ErrNotExist, os.ErrExist, or the equivalent fs.ErrNotExist, not a comparison of error strings. os.IsNotExist predates errors.Is and, officially, should not be the first choice in new code.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
os.MkdirTemp, os.WriteFile, os.ReadFile, os.Stat, os.RemoveAllCreate a temporary directory, write and read a file inside it, and inspect size and permission bits after umask.
os.Stat, os.IsNotExist, errors.Is, os.ErrNotExistDetect a missing file with errors.Is and inspect a PathError without printing its path.
os.OpenFileOpen a file with explicit flags. O_CREATE|O_EXCL fails if the file already exists.

WriteFile, ReadFile, Stat, and MkdirTemp

MkdirTemp creates a directory with a random name, using mode 0o700 before umask. Pass an empty dir to use the default temporary directory; always remove the result when you are finished. WriteFile creates or truncates a file and writes the data. If the file is new, the mode is perm before umask; if it already exists, the data is truncated and the mode is left unchanged. A mid-operation failure can leave a partial file. ReadFile reads the whole file and, like other helpers that read until EOF, returns a nil error on success rather than io.EOF. Stat returns a FileInfo; size and permission bits below were measured on this host.

os.MkdirTemp, os.WriteFile, os.ReadFile, os.Stat, os.RemoveAll

func MkdirTemp(dir, pattern string) (string, error)
func WriteFile(name string, data []byte, perm FileMode) error
func ReadFile(name string) ([]byte, error)
func Stat(name string) (FileInfo, error)
func RemoveAll(path string) error

Create a temporary directory, write and read a file inside it, and inspect size and permission bits after umask.

ParameterDescription
dir, patternMkdirTemp creates a directory in dir. An empty dir uses the default temporary directory. A "*" in pattern is replaced by the random suffix.
name, data, permWriteFile writes data to name with mode perm before umask when it creates the file.

Returns: MkdirTemp returns the new directory path. WriteFile returns an error on failure. ReadFile returns the file contents. Stat returns a FileInfo. RemoveAll removes the path and any children.

Errors

  • *os.PathError — Failed file operations from this package are often of type *PathError, with Op, Path, and Err fields. Check them with errors.Is rather than by matching Path or the error text.
  • The printed permission 0o644 was measured on this host after WriteFile with perm 0o644. A different umask can produce a different mode.
  • The examples never print the temporary path, so the random directory name does not appear in the output.
go
package main

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

func main() {
	dir, err := os.MkdirTemp("", "os-ref-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	name := filepath.Join(dir, "note.txt")
	err = os.WriteFile(name, []byte("hi"), 0o644)
	fmt.Println(err)
	data, err := os.ReadFile(name)
	fmt.Printf("%q %v\n", data, err)
	info, err := os.Stat(name)
	fmt.Printf("%d %#o %v\n", info.Size(), info.Mode().Perm(), err)
}

Expected output

<nil>
"hi" <nil>
2 0644 <nil>

Official documentation →

Errors and OpenFile

Missing-file errors satisfy errors.Is(err, os.ErrNotExist) and errors.Is(err, fs.ErrNotExist), which are the same sentinel. os.IsNotExist also reports true for the Stat error below, but official guidance is to prefer errors.Is in new code. The PathError text "no such file or directory" and "file exists" was measured on darwin/arm64; other systems may word the Err field differently, so portable code should not depend on that string.

Open opens a file read-only. OpenFile is the general call and accepts flags such as O_RDONLY, O_WRONLY, O_RDWR, O_CREATE, O_EXCL, O_TRUNC, and O_APPEND. With O_CREATE|O_EXCL, the file must not already exist; a second call reports os.ErrExist. Create is a helper that truncates or creates with mode 0o666 before umask and opens the file read/write.

os.Stat, os.IsNotExist, errors.Is, os.ErrNotExist

func Stat(name string) (FileInfo, error)
func IsNotExist(err error) bool
var ErrNotExist = fs.ErrNotExist

Detect a missing file with errors.Is and inspect a PathError without printing its path.

ParameterDescription
nameThe path passed to Stat. The example uses a name inside MkdirTemp and never prints that path.
errThe error to test. Prefer errors.Is(err, fs.ErrNotExist) in new code.

Returns: Stat returns a FileInfo and an error. IsNotExist returns whether the error is known to report that a file does not exist.

Errors

  • os.ErrNotExist / fs.ErrNotExist — The portable sentinel for a missing file. It is the same variable.
  • *os.PathError — On this host, a missing file from Stat has Op "stat" and Err "no such file or directory". Use errors.As to read those fields; do not match the full Error string, which includes the path.
  • The printed Err text is from darwin/arm64. Treat it as a measured example, not a portable contract.
go
package main

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

func main() {
	dir, err := os.MkdirTemp("", "os-ref-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	_, err = os.Stat(filepath.Join(dir, "missing.txt"))
	fmt.Println(os.IsNotExist(err), errors.Is(err, os.ErrNotExist), errors.Is(err, fs.ErrNotExist))
	var pe *os.PathError
	if errors.As(err, &pe) {
		fmt.Printf("%s %v\n", pe.Op, pe.Err)
	}
}

Expected output

true true true
stat no such file or directory

Official documentation →

os.OpenFile

func OpenFile(name string, flag int, perm FileMode) (*File, error)
func Open(name string) (*File, error)
func Create(name string) (*File, error)

Open a file with explicit flags. O_CREATE|O_EXCL fails if the file already exists.

ParameterDescription
nameThe file to open. The containing directory must already exist.
flagA bitmask such as O_WRONLY|O_CREATE|O_EXCL. Open is equivalent to OpenFile with O_RDONLY. Create uses O_RDWR and truncates or creates with mode 0o666 before umask.
permUsed only when the file is created. Applied before umask.

Returns: A *File and an error. Close the file when you are finished. The example writes a short string and checks the second exclusive create with errors.Is(err, os.ErrExist).

Errors

  • os.ErrExist — Reported when O_CREATE|O_EXCL is used and the file already exists. On this host the PathError has Op "open" and Err "file exists".
  • *os.PathError — Returned for failed open calls, including a missing file from Open.
  • Do not print PathError.Error() if it would leak a temporary or user path. Print Op and Err, or only the errors.Is result.
go
package main

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

func main() {
	dir, err := os.MkdirTemp("", "os-ref-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	name := filepath.Join(dir, "note.txt")
	f, err := os.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
	fmt.Println(err)
	if err == nil {
		_, _ = f.WriteString("x")
		_ = f.Close()
	}
	_, err = os.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
	fmt.Println(errors.Is(err, os.ErrExist))
	var pe *os.PathError
	if errors.As(err, &pe) {
		fmt.Printf("%s %v\n", pe.Op, pe.Err)
	}
}

Expected output

<nil>
true
open file exists

Official documentation →