Go 1.27 reference · Files, HTTP and Logging
Go os.ReadFile and os.WriteFile Function
Read or write a whole file in one call, with Unix permissions for new files; errors wrap fs.ErrNotExist and friends.
Go 1.27
Syntax
func ReadFile(name string) ([]byte, error) func WriteFile(name string, data []byte, perm FileMode) error
Parameters
| Parameter | Description |
|---|---|
perm |
Permissions for new files, e.g. 0o644. |
os.Create / os.Open |
For streaming reads and writes. |
errors.Is(err, fs.ErrNotExist) |
Check for a missing file. |
Examples
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, _ := os.MkdirTemp("", "demo")
defer os.RemoveAll(dir)
path := filepath.Join(dir, "notes.txt")
if err := os.WriteFile(path, []byte("buy tea\n"), 0o644); err != nil {
panic(err)
}
data, _ := os.ReadFile(path)
fmt.Print(string(data))
}
Output
buy tea
Run this on your computer — see “Get Started” for setup.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func main() {
_, err := os.ReadFile("does-not-exist.txt")
fmt.Println(errors.Is(err, fs.ErrNotExist))
}
Output
true
Run this on your computer — see “Get Started” for setup.
Related
bufio.Scanner· Read input line by line (or word by word) from a file, string or stdin without loading it all into memory.- Go File Handling · tutorial