Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Errors, I/O and Files

Go os package

Reference for the Go os package: files and directories, temp files, environment variables, arguments, standard streams, exit codes and portable error checks.

The os package is Go's portable gateway to the operating system. It opens, creates, renames and removes files and directories, reads environment variables and command-line arguments, exposes the standard streams (Stdin, Stdout, Stderr), reports the working directory and terminates the program with an exit code.

The API is deliberately Unix-flavoured but works the same on Windows, macOS and Linux. Errors from the package are *fs.PathError or *os.LinkError values that wrap sentinel errors such as fs.ErrNotExist, so you can test them with errors.Is regardless of platform.

Go
import "os"

data, err := os.ReadFile("config.json")

Try it

Go A tour of os: temp dir, files and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Environment and standard streams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

The most used declarations, grouped by purpose:

Go
// files
func Open(name string) (*File, error)
func Create(name string) (*File, error)
func OpenFile(name string, flag int, perm FileMode) (*File, error)
func ReadFile(name string) ([]byte, error)
func WriteFile(name string, data []byte, perm FileMode) error

// directories and metadata
func Mkdir(name string, perm FileMode) error
func MkdirAll(path string, perm FileMode) error
func ReadDir(name string) ([]DirEntry, error)
func Stat(name string) (FileInfo, error)
func Remove(name string) error
func RemoveAll(path string) error
func Rename(oldpath, newpath string) error
func MkdirTemp(dir, pattern string) (string, error)
func CreateTemp(dir, pattern string) (*File, error)

// process and environment
func Getenv(key string) string
func LookupEnv(key string) (string, bool)
func Setenv(key, value string) error
func Getwd() (string, error)
func Hostname() (string, error)
func Exit(code int)
var Args []string
var Stdin, Stdout, Stderr *File
Flag constant Meaning
O_RDONLY, O_WRONLY, O_RDWR Exactly one access mode is required.
O_CREATE Create the file if missing.
O_EXCL With O_CREATE, fail if it exists.
O_APPEND Writes go to the end.
O_TRUNC Truncate on open.

Errors: file operations return *fs.PathError. Test with errors.Is(err, fs.ErrNotExist), fs.ErrExist or fs.ErrPermission.

Usage notes

  • Prefer errors.Is(err, fs.ErrNotExist) over the older os.IsNotExist, because it also sees through wrapped errors.
  • Check-then-act is racy. Instead of Stat followed by Create, use OpenFile with O_CREATE|O_EXCL.
  • os.Exit skips deferred functions and does not flush buffered writers. Return from main normally when you can, or put the cleanup before the exit call.
  • perm is masked by the umask on Unix and mostly ignored on Windows. Write it in octal, 0o644.
  • Always close files you open; defer f.Close() right after the error check. For writes, check the error from Close too.
  • Getenv cannot tell empty from unset; use LookupEnv when the difference matters.
  • RemoveAll is dangerous with computed paths. Never pass an empty or user-controlled string without validation.
  • Directory-escape protection: Go 1.24 added os.Root and os.OpenRoot, which confine file operations to a directory tree (symlinks cannot escape it).
  • os.UserHomeDir, os.UserConfigDir and os.UserCacheDir give per-user locations on each platform; os.TempDir returns the temp directory.
  • Reading a whole small file is os.ReadFile; for large files stream with os.Open and bufio.