如果存在文件,如何附加到文件,否则创建一个新文件并写入文件[重复]

This question already has an answer here:

I have a file that I would like to add some contents to. I first check if that file exists. If it does, I add contents to it. If not, I just create a new file with that name and write to it. For this, I am doing something like:

if _, err := os.Stat(filename); os.IsNotExist(err) {
    f, err := os.Create(filename)
    if err != nil {
        panic(err)
    }
        ....
} else {
    f, _ := os.OpenFile(filename, os.O_RDWR|os.O_APPEND, 0660);
    ....
}

Is it possible to make this code shorter like 1-2 liner?

</div>

The OpenFile example shows how to append to existing file or create a new file. The code is:

// 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)
}