Sling Academy
Home/Golang/Parsing CSV Files with the `encoding/csv` Package in Go

Parsing CSV Files with the `encoding/csv` Package in Go

Last updated: November 26, 2024

Parsing CSV (Comma Separated Values) files is a common task in data processing and conversion. Golang offers a built-in package, encoding/csv, which makes it easy to read and write CSV files. In this article, we'll explore how to use this package effectively.

Reading CSV Files

Let's start by understanding how to read a CSV file using this package. Below are the steps and the accompanying code snippets to help you follow along.

Example CSV File

Suppose you have a simple CSV file named data.csv:

Name,Age,Occupation
Alice,30,Engineer
Bob,25,Designer
Charlie,35,Toolmaker

Reading CSV in Go

Here's a basic Go program to read the CSV file:


package main

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

func main() {
    file, err := os.Open("data.csv")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer file.Close()

    reader := csv.NewReader(file)

    records, err := reader.ReadAll()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    for _, record := range records {
        fmt.Println(record)
    }
}

This program opens the CSV file, reads all the records into a two-dimensional slice, and prints each record.

Writing CSV Files

Writing CSV files is similarly straightforward with the encoding/csv package. Here, we will create and write data to a new CSV file.

Writing to a CSV File

Below is an example of how to write data to a CSV file in Go:


package main

import (
    "encoding/csv"
    "os"
)

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

    writer := csv.NewWriter(file)

    data := [][]string{
        {"Name", "Age", "Occupation"},
        {"Alice", "30", "Engineer"},
        {"Bob", "25", "Designer"},
        {"Charlie", "35", "Toolmaker"},
    }

    for _, record := range data {
        if err := writer.Write(record); err != nil {
            panic(err)
        }
    }

    writer.Flush()

    if err = writer.Error(); err != nil {
        panic(err)
    }
}

os.Create is used to create a new CSV file, and csv.NewWriter is used to begin writing to the file. Finally, each record is written and flushed to ensure all buffered operations are executed.

Handling Errors

Error handling is crucial when dealing with files. If you encounter I/O errors, such as permissions issues or file-not-found errors, they must be addressed promptly. In the code examples above, errors have been checked after every critical operation, which is a good practice in Go programming.

Conclusion

The encoding/csv package in Go provides a straightforward API for reading and writing CSV files. Whether you're importing structured data from a CSV file into your application or exporting data for external use, mastering this package will facilitate efficient data handling.

Next Article: Handling Zip Archives Using the `archive/zip` Package in Go

Previous Article: Understanding Little-Endian and Big-Endian with the `encoding/binary` Package

Series: Working with Core package in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant