5

Append text to a file

 3 years ago
source link: https://yourbasic.org/golang/append-to-file/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Append text to a file · YourBasic Go

Append text to a file

yourbasic.org/golang

This code appends a line of text to the file text.log. It creates the file if it doesn’t already exist.

f, err := os.OpenFile("text.log",
	os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
	log.Println(err)
}
defer f.Close()
if _, err := f.WriteString("text to append\n"); err != nil {
	log.Println(err)
}

If you’re appending text to a file for logging purposes, see Write log to file.

Related

Write log to file (or /dev/null)
Use os.OpenFile with arguments os.O_APPEND | os.O_CREATE | os.O_WRONLY and 0644 to create and open a log file. To disable all output from a logger set the output destination to ioutil.Discard.
yourbasic.org
Defer a function call (with return value)
A deferred function is executed when the surrounding function returns, either on exit or on panic. Deferred functions are commonly used for clean-up actions, such as closing a file or unlocking a mutex.
yourbasic.org

Follow on Twitter

Most Read

See all 178 Go articles

This work is licensed under a CC BY 3.0 license.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK