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?
Append mode adds information to an existing file, placing the pointer at the end. If a file does not exist, append mode creates the file.
The "a" mode allows you to open a file to append some content to it. And we want to add a new line to it, we can open it using the "a" mode (append) and then, call the write() method, passing the content that we want to append as argument.
Print the contents of the files before appending using the read() function. Close both the files using the close() function. Open the first file in append mode and the second file in read mode. Append the contents of the second file to the first file using the write() function.
Open file in append mode and write to itOpen the file in append 'a' mode, and write to it using write() method. Inside write() method, a string "new text" is passed. This text is seen on the file as shown above.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With