✒️ Write to a CSV file in Go

June 1, 2021
introduction file

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:

package main

import (

func main() {
    data := [][]string{
        {"vegetables", "fruits"},
        {"carrot", "banana"},
        {"potato", "strawberry"},

    // create a file
    file, err := os.Create("result.csv")
    if err != nil {
    defer file.Close()

    // initialize csv writer
    writer := csv.NewWriter(file)

    defer writer.Flush()

    // write all rows at once

    // write single row
    extraData := []string{"lettuce", "raspberry"}

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.

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings

✍️ Write to a file in Go

Learn how to write any data to a file
introduction file