How to append in a file in go

Oct 5, 2018 22:20 · 111 words · 1 minute read

Here is a snippet which shows how to append data in a file in golang.

We will use os.OpenFile with os._APPEND flag.

package main

import (
	"fmt"
	"os"
)

func main() {

	for i := 0; i < 10; i++ {
		append(fmt.Sprintf("line %d \n", i))
	}
}

func append(text string) {
	f, err := os.OpenFile("myfile.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	f.WriteString(text)
}

Here is a handly list of other flags which can be combined togther and used

FlagDescription
os.O_RDONLYRead only
os.O_WRONLYWrite only
os.O_RDWRRead and write
os.O_APPENDAppend to end of file
os.O_CREATECreate is none exist
os.O_TRUNCTruncate file when opening