By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A file is a resource owned by the operating system, not by Go. Whatever you do with a file - read all of it, scan it line by line, write to it - follows the same three steps: open, use, close. Closing releases the handle back to the operating system so other programs can use the file, and so your own program does not leak handles.
Two functions cover most of what you will ever need. os.WriteFile(path, data, permissions) writes a whole []byte to a file, creating it or truncating it. os.ReadFile(path) returns the whole file as a []byte. Each one opens and closes the file internally, so there is no handle to forget.
package main
import (
"fmt"
"os"
)
func main() {
path := "notes.txt"
err := os.WriteFile(path, []byte("coffee: 450\nbus: 300\n"), 0644)
if err != nil {
fmt.Println("write failed:", err)
return
}
data, err := os.ReadFile(path)
if err != nil {
fmt.Println("read failed:", err)
return
}
fmt.Print(string(data))
fmt.Println("bytes read:", len(data))
}A []byte is the raw form of text. []byte("...") converts a string to bytes, and string(data) converts back. Go makes that conversion explicit because bytes and text are not the same thing, even when the bytes happen to be ASCII.
When you want to process a file line by line, or when you are writing the file yourself rather than letting a helper do it, you hold the handle directly. os.Create opens a file for writing, creating it if needed. os.Open opens an existing file for reading.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
write, err := os.Create("notes.txt")
if err != nil {
fmt.Println("create failed:", err)
return
}
_, err = write.WriteString("coffee: 450\nbus: 300\n")
write.Close()
if err != nil {
fmt.Println("write failed:", err)
return
}
file, err := os.Open("notes.txt")
if err != nil {
fmt.Println("open failed:", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println("line:", scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("scan failed:", err)
return
}
fmt.Println("done: defer will close the file when main returns")
}defer file.Close() sits immediately after the error check, before the code that uses the file. That placement is a habit worth copying: the close is scheduled at the moment the open succeeds, so later edits cannot accidentally skip it.
The third argument to os.WriteFile is an octal permission number. 0644 means: the owner can read and write, and everyone else can read. It is the usual choice for data files. 0600 is private to the owner, which matters for files with secrets. The operating system applies these rules, so the meaning stays the same on every platform Go runs on.
| Mode | Owner | Group and others | Typical use |
|---|---|---|---|
0600 | read and write | nothing | Private data, keys |
0644 | read and write | read only | Ordinary data files |
0755 | read and write | read and execute | Programs and folders |
%wFile operations fail for reasons the caller needs to understand: the file does not exist, the path is a folder, the disk is full, permission is denied. Wrap the error with %w and add the path so the message says what failed, while errors.Is still lets the caller test the original cause.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
// readLines returns the file contents, wrapping any error with context.
func readLines(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("readLines(%q): %w", path, err)
}
return string(data), nil
}
func main() {
text, err := readLines("missing.txt")
if err != nil {
fmt.Println("could not read the file")
if errors.Is(err, fs.ErrNotExist) {
fmt.Println("reason: the file does not exist")
}
return
}
fmt.Println("contents:", text)
}fs.ErrNotExist is the sentinel for a missing file, and fs.ErrPermission is the one for permission problems. Testing with errors.Is means the same check works whether the error came directly from os.ReadFile or from a function that wrapped it three times on the way up.
Write a function func copyFile(from, to string) error that reads the source with os.ReadFile and writes it with os.WriteFile, wrapping each error with %w and the path. Call it with a file you create first, then call it again with a file that does not exist. Print the error from the second call and check it with errors.Is(err, fs.ErrNotExist).
Key takeaways
Every file follows open, use, close; the helpers do all three for you.
os.ReadFile and os.WriteFile handle whole files; os.Open, os.Create and defer Close give control.
defer file.Close() goes right after the error check so every return path closes the handle.
0644 is the usual data-file permission: owner read/write, everyone else read.
Wrap file errors with %w and the path; test them with errors.Is and fs.ErrNotExist.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.