Skip to content

Writing files

Write files using os.WriteFile (entire content) or os.Create + io.WriteString (incremental). Always close files after writing.

Write a string to a file.

package main
import (
"fmt"
"os"
)
func main() {
content := []byte("Hello, file!")
err := os.WriteFile("output.txt", content, 0644)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("File written successfully")
}
Terminal window
File written successfully