Go by Example

Writing Files

Write small files with os.WriteFile; stream with bufio.Writer, append with os.OpenFile, and call Sync when durability is required.

Use os.WriteFile for small, complete outputs. It creates or truncates the file, then writes the supplied bytes.

Check the returned error. The permission argument applies when creating a new file; it does not change permissions on an existing file.

package main
 
import (
    "fmt"
    "os"
)
 
func main() {
    data := []byte("hello, file\n")
    if err := os.WriteFile("output.txt", data, 0600); err != nil {
        panic(err)
    }
    fmt.Println("wrote", len(data), "bytes")
}

In production

For streamed output, use bufio.Writer and check Flush before closing the file. Use os.OpenFile with O_APPEND to append instead of truncating. Call File.Sync when the application requires data to reach storage before reporting success. For a rename-based replacement, close a temporary file in the target directory before renaming it. Rename atomicity and overwrite behavior are platform-specific, so check those guarantees when they matter.

Enjoyed this? Get more software craft delivered to your inbox.