Understand the contract
os.ReadFile reads a complete file into memory, while os.WriteFile writes a byte slice to a path. These helpers fit small local configuration or practice files. For large or continuous input, open the file and process it through io.Reader instead of loading everything at once.
The example creates a temporary directory so it does not overwrite an existing notes.txt in your project. filepath.Join builds a path appropriate for the operating system. Deferred cleanup runs when run returns. The write permission is meaningful under Unix permission rules; platform behavior can differ.
Work through the example
run returns errors to main and only prints content after both operations succeed. WriteFile may truncate an existing target, which is another reason to use the private temporary directory here. The resulting string includes a newline, so Print rather than Println avoids adding a second one.
package main
import (
"fmt"
"os"
"path/filepath"
)
func run() error {
dir, err := os.MkdirTemp("", "go-lesson-*")
if err != nil { return err }
defer os.RemoveAll(dir)
path := filepath.Join(dir, "notes.txt")
if err := os.WriteFile(path, []byte("learn Go\n"), 0600); err != nil { return err }
data, err := os.ReadFile(path)
if err != nil { return err }
fmt.Print(string(data))
return nil
}
func main() { if err := run(); err != nil { fmt.Println(err) } }Watch this boundary
Direct writes are not automatically atomic updates. If another process must never observe a partial replacement, design a temporary-file and rename workflow appropriate to the filesystem and durability requirements. Also handle cleanup errors when their outcome matters; this educational example uses best-effort removal of its temporary data.
Practice with a changed input
Change the payload to Unicode text and compare the byte length with its rune count. Then attempt a read of a missing filename and inspect the returned error.
Lesson 33 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services