CSV is a popular data format used by Excel, Google Sheets and other spreadsheet apps to save and load tabular data. In this format, rows are separated by a newline character and each cell in a row is separated by a comma (or a tab in TSV format). Go has great built-in support for writing and reading CSV files. Check out how easy it is to write a simple CSV file.
See also our example of how to read a CSV file in Go
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
data := [][]string{
{"vegetables", "fruits"},
{"carrot", "banana"},
{"potato", "strawberry"},
}
// create a file
file, err := os.Create("result.csv")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// initialize csv writer
writer := csv.NewWriter(file)
defer writer.Flush()
// write all rows at once
writer.WriteAll(data)
// write single row
extraData := []string{"lettuce", "raspberry"}
writer.Write(extraData)
}
In the first step, you need to create a file where the CSV data can be saved. You can do this with the Create
function from the os
package. Be sure to call file.Close()
to close the file after the data has been written.
Then, we initialize csv.Writer
from the encoding/csv
package, that allows us to write data in CSV format. It’s a buffered writer, so we should call writer.Flush()
at the end of the write to make sure all data is saved to the file.
The CSV writer has two methods for saving data rows. We can use writer.WriteAll()
method when we know all the data at the time of writing, or writer.Write()
to write the data line by line.
Write to a TSV file
The standard separator of csv.Writer
is a comma, but you can easily change this by replacing the comma rune with another character:
writer.Comma = '\t'
In this way, our writer uses TSV (tab-separated values) encoding that is also a commonly used tabular data format.