Appending to Files in Go
In Go, reading from a local file is straightforward using ioutil.ReadFile. Similarly, writing to a file can be done using ioutil.WriteFile. However, when it comes to appending to an existing file, there is no built-in method that directly handles this.
Solution
To append to a file in Go, you can use the following steps:
Open the file using os.OpenFile, specifying the following flags:
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { panic(err) }
if _, err = f.WriteString(text); err != nil { panic(err) }
defer f.Close()
By following these steps, you can effectively append data to an existing file in Go.
The above is the detailed content of How to Append Data to a File in Go?. For more information, please follow other related articles on the PHP Chinese website!