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 to save a small, complete result. It creates the file if needed or clears an existing file before writing the supplied bytes.

Check the returned error to see whether the write succeeded. The permission number applies only when creating a new file; it does not change the permissions on an existing one.

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 output written in pieces, use bufio.Writer to collect text before writing and call Flush to send it to the file. Use os.OpenFile with O_APPEND to add data to the end instead of clearing the file. File.Sync asks the operating system to save file data to storage before the program reports success. These steps matter when losing recent data would be costly.

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