Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to a file in Go

Tags:

file-io

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?

like image 406
seveibar Avatar asked Aug 22 '11 17:08

seveibar


People also ask

How do I read a file in Golang?

In Go, the ReadFile() function of the ioutil library is used to read data from a file. Using ioutil makes file reading easier as you don't have​ to worry about closing files or using buffers.

Can you append to a file in python?

The best practice for writing to, appending to, and reading from text files in Python is using the with keyword. Breakdown: You first start off with the with keyword. Next, you open the text file.


2 Answers

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) } 
like image 90
Sridhar Ratnakumar Avatar answered Oct 01 '22 15:10

Sridhar Ratnakumar


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)     } } 
like image 35
Jimmy Obonyo Abor Avatar answered Oct 01 '22 13:10

Jimmy Obonyo Abor