0PricingLogin
Go Academy · Lesson

Writing Files and Temp Files

WriteFile, OpenFile flags, and temp files

os.WriteFile

os.WriteFile writes a byte slice to a file atomically (truncate then write). Simple for small files.

err := os.WriteFile("output.txt", []byte("hello"), 0644)
if err != nil { log.Fatal(err) }

os.Create and defer Close

os.Create creates or truncates a file and returns an *os.File. Always close with defer.

f, err := os.Create("output.txt")
if err != nil { return err }
defer f.Close()
f.WriteString("hello\n")

All lessons in this course

  1. Reading Files with os and bufio
  2. Writing Files and Temp Files
  3. JSON Encoding and Decoding
  4. Streaming JSON and CSV
← Back to Go Academy