}

Go: How to write/read data to a CSV file?

Created:

Introducion

CSV format is a popular non-standaried file formar. The file has a row per line and each line could contain several fields, usually separated by command. Some CSV files could contain command in the data and the separator could be changed to another one.

In this brief tutorial we are going to Go to write a CSV using the encoding/csv package.

Writing data

We will use a multi dimensional array with strings. We will iterate this array and save it to a .csv file.

    package main

    import (
        "os"
        "log"
        "encoding/csv"
    )

    var data = [][]string{
        {"Row 1", "30"}, 
        {"Row 2", "60"},
        {"Row 3", "90"}}

    func main() {
        file, err := os.Create("tutorials_technology.csv")
        if err != nil {
            log.Fatal(err)
        }
        defer file.Close()

        w := csv.NewWriter(file) 

        for _, value := range data {
            if err := w.Write(value); err != nil {
                log.Fatalln("Error writing record to csv: ", err)
            }
        }
        w.Flush()
    }

After the execution the file generated should contain:

Row 1, 30 Row 2, 60 Row 3, 90

If you want to configure the output, check the encoding/csv documentation. NewWriter returns a Writer that writes records terminated by a newline and uses ',' as the field delimiter.

If you want to change the separator use the following code:

writer = csv.NewWriter(w)
writer.Comma = '\t'

The code above will change ',' with '\t' as separator and will use tab spaces as separator.

Reading data

package main

import (
    "os"
    "log"
    "encoding/csv"
)

func main() {
    reader := csv.NewReader(csvFile)

    reader.Comma = ',' # you can change it to \t in case you use tab separator

    reader.FieldsPerRecord = -1

    if csvData, err := reader.ReadAll(); err != nil {
        log.Fatalln("Error reading csv file :  ", err)
    }
}

On csvData you will have all the records on the that you can iterate later.