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
- Reading Files with os and bufio
- Writing Files and Temp Files
- JSON Encoding and Decoding
- Streaming JSON and CSV