Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Append to an existing file in Go (Golang)

Posted on January 17, 2020January 17, 2020 by admin

os.OpenFile() function of the os package can be used to open to a file in an append mode and then write to it

Let’s see an example. In the below program:

  • First, write to a file using ioutil package
  • Open the file again in Append mode and write the second line to it
  • Read the file to verify the content.
package main

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

func main() {
    //Write first line
    err := ioutil.WriteFile("temp.txt", []byte("first line\n"), 0644)
    if err != nil {
        log.Fatal(err)
    }
    
    //Append second line
    file, err := os.OpenFile("temp.txt", os.O_APPEND|os.O_WRONLY, 0644)
    if err != nil {
        log.Println(err)
    }
    defer file.Close()
    if _, err := file.WriteString("second line"); err != nil {
        log.Fatal(err)
    }
    
    //Print the contents of the file
    data, err := ioutil.ReadFile("temp.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(data))
}

Output:

first line
second line
  • file
  • go
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme