How to append text to a file in Golang?


The OpenFile function with os.O_APPEND opens the already exist file test.txt in append mode. WriteString function write the content at the end of the file.

Example

package main

import (
	"io/ioutil"
	"log"
	"fmt"
	"os"
)

func AppendFile() {		
	file, err := os.OpenFile("test.txt", os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		log.Fatalf("failed opening file: %s", err)
	}
	defer file.Close()

	len, err := file.WriteString(" The Go language was conceived in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google.")
	if err != nil {
		log.Fatalf("failed writing to file: %s", err)
	}
	fmt.Printf("\nLength: %d bytes", len)
	fmt.Printf("\nFile Name: %s", file.Name())
}

func ReadFile() {
	data, err := ioutil.ReadFile("test.txt")
	if err != nil {
		log.Panicf("failed reading data from file: %s", err)
	}
	fmt.Printf("\nLength: %d bytes", len(data))
	fmt.Printf("\nData: %s", data)
	fmt.Printf("\nError: %v", err)
}

func main() {
	fmt.Printf("######## Append file #########\n")
	AppendFile()
	
	fmt.Printf("\n\n######## Read file #########\n")
	ReadFile()
}

Output

######## Append file #########

Length: 107 bytes
File Name: test.txt

######## Read file #########

Length: 246 bytes
Data: The Go Programming Language, also commonly referred to as Golang, is a general-purpose programming language, developed by a team at Google. The Go language was conceived in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google.
Error: 
Most Helpful This Week