Go · Stage 8 – Errors and Files · Lesson 49 of 64

Writing to a File

Write text with an explicit file permission.

Go code

err := os.WriteFile("note.txt", []byte("Hello"), 0644)
if err != nil {
    fmt.Println("Could not write file")
    return
}
fmt.Println("Saved")
Line-by-line explanation
  1. WriteFile selects the path.
  2. The string is converted to bytes.
  3. 0644 is the new file permission on Unix-like systems.
  4. The error is checked.
  5. Saved confirms success.
Expected output
Saved

This is the expected result.

WriteFile replaces an existing file. The permission value matters when a new file is created.