Working with CSV in GO

Barun Thapa
3 min readJun 2, 2019

--

Photo by Mika Baumeister on Unsplash

In this tutorial, we will look at a simple way to read and write CSV files in Golang.

We’ll be using packages from Golang’s standard library encoding/csv to read the csv files, and os to work with the files.

Reading a CSV file

Let’s first create a CSV file -> records.csv
with following contents

Name,Age,Country
Robin Van Persie,34,Netherlands
Wayne Rooney,33,England
Luka Modric,32,Croatia

We’ll create a csvreader.go file with a csvReader() function that will read the csv file.

package mainimport (
"encoding/csv"
"fmt"
"os"
)
func main() {
csvReader()
}
func csvReader() {
...
}

Now let’s build the csvReader function.

func csvReader() {
// 1. Open the file
recordFile, err := os.Open("./records.csv")
if err != nil {
fmt.Println("An error encountered ::", err)
}
// 2. Initialize the reader
reader := csv.NewReader(recordFile)
// 3. Read all the records
records, _ := reader.ReadAll()
// 4. Iterate through the records as you wish
fmt.Println(records)
}

In above function, first step is to read the local file. We have used os.Open(<filepath>) to open our records.csv file.

Then, we create a Reader by calling csv.NewReader(<io source>). A Reader reads records from a CSV-encoded file. If we need any customization on how the data is read or processed, we can do it in the reader. Example:

reader := csv.NewReader(recordFile)
// Separator
reader.Comma = "\t" // when records are separated by tab
reader.Comment = "#" // ignores the line starting with '#'

More about the reader here.

Third step is to read the data using ReadAll() function on reader. This function will extract all the content of the file at once. There is another Read() function that will read one line at a time. I’ll list the usage later on.

records, _ := reader.ReadAll()

The records will be a slice of slices with string data type( [][]string ).
Keep this in mind when you have numeric data to work with.

Then you can iterate over the data as needed. In above snippet, I’ve just printed those out which gives the output as:

[[Name Age Country] [Robin Van Persie 34 Netherlands] [Wayne Rooney 33 England] [Luka Modric 32 Croatia]]

Here is the full program, using both read implementations

Writing a CSV file

Now that we have learned how to read from a CSV file, lets take a look into how we can write one. We’ll use the same packages os and csv/encoding, and io which provides basic interfaces to I/O.

We’ll create a csvWriter.go file with a csvWriter() function that will write to a csv file.

package mainimport (
"encoding/csv"
"fmt"
"os"
)
func main() {
csvWriter()
}
func csvWriter() {
...
}

Now, let’s build csvWriter function.

func csvWriter() {
// 1. Open the file
recordFile, err := os.Create("./superheroes.csv")
if err != nil {
fmt.Println("An error encountered ::", err)
}

// 2. Initialize the writer
writer := csv.NewWriter(recordFile)
var csvData = [][]string{
{"SuperHero Name", "Power", "Weakness"},
{"Batman", "Wealth", "Human"},
{"Superman", "Strength", "Kryptonite"},
}
// 3. Write all the records
err = writer.WriteAll(csvData) // returns error
if err != nil {
fmt.Println("An error encountered ::", err)
}
}

In the above csvWriter() function, we are creating a file superheroes.csv via os.Create() function.

Then, we set up a writer using NewWriter(<io source>) from csv package to write torecordFile .

Finally, we write the csvData to the file using WriteAll(records [][]string) function of the writer. Alternately, we can also use Write(record []string) function that will write one row/line at a time. Both these functions return an error type.

Here is the a sample program to write to a csv file.

--

--

Barun Thapa

Computer Engineer, Ruby on Rails developer, Red Devil, supporter of Holland and Brazil.