[Golang] Append Line/String to File


I summarize the answer [1] [2] on Stack Overflow and write a func for the ease of use.

import "os"

/**
 * Append string to the end of file
 *
 * path: the path of the file
 * text: the string to be appended. If you want to append text line to file,
 *       put a newline '\n' at the of the string.
 */
func AppendStringToFile(path, text string) error {
      f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
      if err != nil {
              return err
      }
      defer f.Close()

      _, err = f.WriteString(text)
      if err != nil {
              return err
      }
      return nil
}

Tested on:

  • Ubuntu Linux 16.10
  • Go 1.7.4

References:

[1]Append to a file in Go - Stack Overflow
[2]go - Golang bad file descriptor - Stack Overflow