We saw how easy it is to read from file in golang in my previous post here
In this post, we will see how to write to the file, we will again use bufio package.
First create file to we wish to write to (It points to file, if it exist already)
You can pass relative(../file_name) or abosulte path(C:/folder_name/file_name) of file to Open method.
We will add a defer statement to close file, so that once our work is done file handle is closed,
Now we need Writer for writing line, we can create it using bufio package as
Now simply write following line to write line to file -
And finally do not forget to flush writer as
The complete code is as below -
Note:- I am using “_” for error, and not handling the error, but should be done in your production code, read about error handling here
But if you have observed here, in case where file already exists, the file content are overwritten, so how to keep the original content and append text to file ?
To do that we will open file in append mode as
fileHandle, _ := os.OpenFile("output.txt", os.O_APPEND, 0666)
Read about OpenFile
And rest remains the same as earlier, complete code -
We can combine previous post code and this post code to read from file, apply some transformation if needed and then write/append to file.