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.
import "os" data, err := os.ReadFile("config.json")
Try it
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.
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:
// 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 olderos.IsNotExist, because it also sees through wrapped errors. - Check-then-act is racy. Instead of
Statfollowed byCreate, useOpenFilewithO_CREATE|O_EXCL. os.Exitskips deferred functions and does not flush buffered writers. Return frommainnormally when you can, or put the cleanup before the exit call.permis 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 fromClosetoo. Getenvcannot tell empty from unset; useLookupEnvwhen the difference matters.RemoveAllis dangerous with computed paths. Never pass an empty or user-controlled string without validation.- Directory-escape protection: Go 1.24 added
os.Rootandos.OpenRoot, which confine file operations to a directory tree (symlinks cannot escape it). os.UserHomeDir,os.UserConfigDirandos.UserCacheDirgive per-user locations on each platform;os.TempDirreturns the temp directory.- Reading a whole small file is
os.ReadFile; for large files stream withos.Openandbufio.