Skip to content

Append text to file in Go

Advertisements

Syntax

filePath.WriteString(content)

Examples

An example from Github.

package main

import (
	"log"
	"os"
)

func main() {
	// Append and write to file
	appendAndWriteToFile("codes/hex/1", "DE34566")
}

// Append and write to file
func appendAndWriteToFile(path string, content string) {
	filePath, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatalln(err)
	}
	_, err = filePath.WriteString(content + "\n")
	if err != nil {
		log.Fatalln(err)
	}
	err = filePath.Close()
	if err != nil {
		log.Fatalln(err)
	}
}
See also  Replace all occurrences of a string in Go

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.