file-iogo

Append to a file in Go


So I can read from a local file like so:

data, error := ioutil.ReadFile(name)

And I can write to a local file

ioutil.WriteFile(filename, content, permission)

But how can I append to a file? Is there a built in method?


Solution

  • This answers works in Go1:

    f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
    if err != nil {
        panic(err)
    }
    
    defer f.Close()
    
    if _, err = f.WriteString(text); err != nil {
        panic(err)
    }