To write to a CSV file in Go, we can use the encoding/csv
package. Here's an example of how to do it:
main.go436 chars26 lines
In this example, the writeCSV
function takes a filename
string and a 2D string slice data
as parameters. The filename
parameter specifies the output CSV file name, while data
represents the data that we want to write to the file.
Inside the function, we first create a file object using the os.Create
function. We check for errors and defer the file.Close()
function call to make sure that the file is closed after we're done writing to it.
Next, we create a CSV writer object using csv.NewWriter
, passing it a buffer created with bufio.NewWriter
. We also defer writer.Flush()
to make sure that any remaining CSV output is flushed to the file before we close it.
Finally, we loop through the rows in data
and write each row to the CSV file using writer.Write
. The Write
function returns an error if something went wrong, so we check for and return any errors encountered in the process.
Here's an example of how to use the writeCSV
function:
main.go278 chars12 lines
In this example, we create a 2D string slice named data
containing some sample data, then call writeCSV
and pass it the output filename and data
slice as parameters. If an error occurs while writing to the output file, we panic and print the error message.
gistlibby LogSnag