Write data to a CSV file

· 211 words · 1 minute read

CSV is a highly accepted data language, commonly used by Excel and spreadsheets, and as such is very useful if your script is producing data and you want it in a common format.

In the example, we’re forming a data variable, just to illustrate the example, by creating a multi-dimensional array of strings. We are then having to create a file (result.csv) for the csv writer to work with. Finally, we are iterating through the data writing each line to the file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

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

var data = [][]string{{"Line1", "Hello Readers of"}, {"Line2", "golangcode.com"}}

func main() {
    file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()

    writer := csv.NewWriter(file)
    defer writer.Flush()

    for _, value := range data {
        err := writer.Write(value)
        checkError("Cannot write to file", err)
    }
}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }
}

The result:

Line1,Hello Readers of
Line2,golangcode.com

This process is possible through two packages, os and encoding/csv - one which handles the file interactions the other which converts the data structure into csv format.

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!