Writing to a File
·
223 words
·
2 minutes read
Often it’s very useful being able to write to a file from a program for logging purposes, saving results or as a data store. This is a little snippet on how to write text/data to a file.
We use the os
package to create the file, exiting the program and logging if it can’t do this and printing a string into the file using io.WriteString
. We’re also using defer to close the file access once the function has finished running (which is a really neat way of remembering to close files). With a final file sync on close to prevent any un-caught errors (see this post for info).
|
|