Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers.
File Operations
Opening Files
Open
func Open(name string) (*File, error)
Opens the named file for reading. If successful, methods on the returned file can be used for reading.file, err := os.Open("config.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
Create
func Create(name string) (*File, error)
Creates or truncates the named file. If the file already exists, it is truncated. The file is opened with mode 0666.file, err := os.Create("output.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
OpenFile
func OpenFile(name string, flag int, perm FileMode) (*File, error)
Opens a file with specified flags and permissions. This is the generalized open call.// Open for append
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
File Flags
Append data to the file when writing
Create a new file if none exists
Used with O_CREATE, file must not exist
Truncate regular writable file when opened
File Methods
File.Read
func (f *File) Read(b []byte) (n int, err error)
Reads up to len(b) bytes from the file. Returns the number of bytes read and any error encountered.data := make([]byte, 100)
n, err := file.Read(data)
File.Write
func (f *File) Write(b []byte) (n int, err error)
Writes len(b) bytes to the file. Returns the number of bytes written and any error encountered.n, err := file.Write([]byte("Hello, World!"))
File.WriteString
func (f *File) WriteString(s string) (n int, err error)
Writes a string to the file. Returns the number of bytes written.n, err := file.WriteString("Hello, World!\n")
File.Close
func (f *File) Close() error
Closes the file, rendering it unusable for I/O. Always defer Close after opening a file.
File.Seek
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
Sets the offset for the next Read or Write. Returns the new offset.// Seek to beginning
file.Seek(0, io.SeekStart)
// Seek to end
file.Seek(0, io.SeekEnd)
File.Stat
func (f *File) Stat() (FileInfo, error)
Returns the FileInfo structure describing file. Can be used to get file size, permissions, modification time, etc.info, err := file.Stat()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Size: %d bytes\n", info.Size())
Stat
func Stat(name string) (FileInfo, error)
Returns a FileInfo describing the named file.info, err := os.Stat("example.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("Size:", info.Size())
fmt.Println("Modified:", info.ModTime())
fmt.Println("Is directory:", info.IsDir())
Lstat
func Lstat(name string) (FileInfo, error)
Like Stat but if the file is a symbolic link, it returns information about the link itself.
Describes a file and is returned by Stat and Lstat.type FileInfo interface {
Name() string // base name of the file
Size() int64 // length in bytes
Mode() FileMode // file mode bits
ModTime() time.Time // modification time
IsDir() bool // is a directory
Sys() any // underlying data source
}
Directory Operations
Mkdir
func Mkdir(name string, perm FileMode) error
Creates a new directory with the specified name and permission bits.err := os.Mkdir("testdir", 0755)
if err != nil {
log.Fatal(err)
}
MkdirAll
func MkdirAll(path string, perm FileMode) error
Creates a directory named path, along with any necessary parents. If path is already a directory, MkdirAll does nothing.err := os.MkdirAll("path/to/dir", 0755)
Remove
func Remove(name string) error
Removes the named file or empty directory.err := os.Remove("oldfile.txt")
RemoveAll
func RemoveAll(path string) error
Removes path and any children it contains. It removes everything it can but returns the first error encountered.err := os.RemoveAll("temp_directory")
ReadDir
func ReadDir(name string) ([]DirEntry, error)
Reads the named directory and returns a list of directory entries sorted by filename.entries, err := os.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
fmt.Println(entry.Name())
}
File Content Operations
ReadFile
func ReadFile(name string) ([]byte, error)
Reads the named file and returns the contents. A successful call returns err == nil.data, err := os.ReadFile("config.json")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
WriteFile
func WriteFile(name string, data []byte, perm FileMode) error
Writes data to the named file, creating it if necessary. If the file exists, WriteFile truncates it before writing.data := []byte("Hello, World!")
err := os.WriteFile("output.txt", data, 0644)
if err != nil {
log.Fatal(err)
}
Path Operations
Getwd
func Getwd() (dir string, err error)
Returns a rooted path name corresponding to the current directory.dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
fmt.Println("Current directory:", dir)
Chdir
func Chdir(dir string) error
Changes the current working directory to the named directory.
Rename
func Rename(oldpath, newpath string) error
Renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it.err := os.Rename("old.txt", "new.txt")
Process Operations
Getenv
func Getenv(key string) string
Retrieves the value of the environment variable named by the key. Returns empty string if the variable is not present.home := os.Getenv("HOME")
path := os.Getenv("PATH")
Setenv
func Setenv(key, value string) error
Sets the value of the environment variable named by the key.err := os.Setenv("API_KEY", "secret123")
Returns a copy of strings representing the environment in the form “key=value”.for _, env := range os.Environ() {
fmt.Println(env)
}
Causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error.if err != nil {
os.Exit(1)
}
Standard File Descriptors
Open File pointing to standard inputscanner := bufio.NewScanner(os.Stdin)
Open File pointing to standard outputfmt.Fprintln(os.Stdout, "Hello")
Open File pointing to standard errorfmt.Fprintln(os.Stderr, "Error occurred")
Examples
Reading a File
package main
import (
"fmt"
"log"
"os"
)
func main() {
// Simple way - read entire file
data, err := os.ReadFile("example.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
// Advanced way - streaming read
file, err := os.Open("example.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
buffer := make([]byte, 1024)
for {
n, err := file.Read(buffer)
if err != nil {
break
}
fmt.Print(string(buffer[:n]))
}
}
Writing to a File
package main
import (
"log"
"os"
)
func main() {
// Simple way
data := []byte("Hello, World!\n")
err := os.WriteFile("output.txt", data, 0644)
if err != nil {
log.Fatal(err)
}
// Append to file
file, err := os.OpenFile("log.txt",
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
file.WriteString("New log entry\n")
}
Working with Directories
package main
import (
"fmt"
"log"
"os"
)
func main() {
// Create directory
err := os.MkdirAll("path/to/dir", 0755)
if err != nil {
log.Fatal(err)
}
// List directory contents
entries, err := os.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
info, _ := entry.Info()
fmt.Printf("%s\t%d bytes\n", entry.Name(), info.Size())
}
}
Environment Variables
package main
import (
"fmt"
"os"
)
func main() {
// Get environment variable
home := os.Getenv("HOME")
fmt.Println("Home directory:", home)
// Set environment variable
os.Setenv("MY_VAR", "my_value")
// Check if exists
value, exists := os.LookupEnv("MY_VAR")
if exists {
fmt.Println("MY_VAR =", value)
}
}