Append to a file in Go

2019-01-16 08:14发布

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?

标签: file-io go
5条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-16 08:26

If you also want to create the file

f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)

查看更多
\"骚年 ilove
3楼-- · 2019-01-16 08:28

This answers works in Go1:

f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
    panic(err)
}

defer f.Close()

if _, err = f.WriteString(text); err != nil {
    panic(err)
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-16 08:28

... I would use fmt.Fprintf, because accept a writer... and a connection or files will be a writer and easy to write in a way of string...

f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
    panic(err)
}

defer f.Close()
fmt.Fprintf(f, "%s", text)

I hope this help!

Javier,

查看更多
可以哭但决不认输i
5楼-- · 2019-01-16 08:43

Figured it out

More info

f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644) 

n, err := f.WriteString(text) 

f.Close()
查看更多
一纸荒年 Trace。
6楼-- · 2019-01-16 08:49

Go docs has a perfect example :

package main

import (
    "log"
    "os"
)

func main() {
    // If the file doesn't exist, create it, or append to the file
    f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatal(err)
    }
    if _, err := f.Write([]byte("appended some data\n")); err != nil {
        log.Fatal(err)
    }
    if err := f.Close(); err != nil {
        log.Fatal(err)
    }
}
查看更多
登录 后发表回答