0
0
GoHow-ToBeginner · 3 min read

How to Append to File in Go: Simple Guide with Example

To append to a file in Go, use os.OpenFile with the flags os.O_APPEND and os.O_CREATE. Then write your data using Write or WriteString methods and close the file.
📐

Syntax

Use os.OpenFile with these flags to open a file for appending:

  • os.O_APPEND: Add data to the end of the file.
  • os.O_CREATE: Create the file if it does not exist.
  • os.O_WRONLY: Open the file for writing only.

Then use Write or WriteString to add content.

go
file, err := os.OpenFile("filename.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
    // handle error
}
_, err = file.WriteString("text to append\n")
if err != nil {
    // handle error
}
file.Close()
💻

Example

This example opens or creates a file named example.txt and appends a line of text to it. It shows how to handle errors and close the file properly.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.OpenFile("example.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    _, err = file.WriteString("Hello, this line is appended!\n")
    if err != nil {
        fmt.Println("Error writing to file:", err)
        return
    }

    fmt.Println("Successfully appended to file.")
}
Output
Successfully appended to file.
⚠️

Common Pitfalls

Common mistakes when appending to files in Go include:

  • Not using os.O_APPEND flag, which causes overwriting instead of appending.
  • Forgetting to close the file, which can cause data loss.
  • Not handling errors from OpenFile or WriteString.

Always check errors and close files properly.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Wrong: Missing os.O_APPEND flag
    file, err := os.OpenFile("wrong.txt", os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer file.Close()

    _, err = file.WriteString("This will overwrite the file.\n")
    if err != nil {
        fmt.Println("Write error:", err)
        return
    }

    fmt.Println("File written without append flag.")
}
Output
File written without append flag.
📊

Quick Reference

  • os.O_APPEND: Append data to the file.
  • os.O_CREATE: Create file if missing.
  • os.O_WRONLY: Open file for writing only.
  • 0644: File permission (read/write for owner, read for others).
  • Always Close() the file after writing.

Key Takeaways

Use os.OpenFile with os.O_APPEND|os.O_CREATE|os.O_WRONLY flags to append to a file.
Always check for errors when opening and writing to files.
Remember to close the file to save changes properly.
Without os.O_APPEND, writing will overwrite the file content.
File permissions like 0644 control who can read or write the file.