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
How to add and update elements in Map?
Regular expression to extract date(YYYY-MM-DD) from string
Creating a Function in Golang
Example: Arrays of Arrays, Arrays of Slices, Slices of Arrays and Slices of Slices
How to reads and decodes JSON values from an input stream?
How to use wildcard or a variable in our URL for complex routing?