Golang
Golang

 

 

Introduction

CSV (Comma-Separated Values) files are widely used for storing and exchanging tabular data. Parsing a CSV file and displaying its contents is a common task in data processing pipelines. This program demonstrates how to use Go (Golang) to read a CSV file and print its contents to the terminal.

Objective

The objective of this program is to take a CSV file as input, parse its contents, and display the data row by row in the terminal. This program serves as an introduction to handling CSV files in Go using the encoding/csv package.

Code

        package main

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

        func main() {
            // Open the CSV file
            file, err := os.Open("data.csv")
            if err != nil {
                fmt.Fprintf(os.Stderr, "Error opening file: %v\n", err)
                os.Exit(1)
            }
            defer file.Close()

            // Create a new CSV reader
            reader := csv.NewReader(file)

            // Read all rows from the CSV file
            records, err := reader.ReadAll()
            if err != nil {
                fmt.Fprintf(os.Stderr, "Error reading CSV file: %v\n", err)
                os.Exit(1)
            }

            // Print the contents of the CSV file
            fmt.Println("CSV Contents:")
            for i, row := range records {
                fmt.Printf("Row %d: %v\n", i+1, row)
            }
        }

Explanation

This program performs the following steps:

  1. Import necessary packages: The program uses encoding/csv for parsing CSV files and os for file operations.
  2. Open the CSV file: The program opens a file named data.csv. Ensure this file exists in the same directory as the program.
  3. Create a CSV reader: A CSV reader is created to read the file contents.
  4. Read all rows: The program reads all rows from the CSV file using reader.ReadAll(). Each row is stored as a slice of strings.
  5. Print the rows: The rows are iterated over, and each row is printed with its index.

How to Run

  1. Install Go from the official Go website.
  2. Create a CSV file named data.csv in the same directory as the program. For example:
    Name,Age,City
    John,30,New York
    Jane,25,Los Angeles
    Bob,35,Chicago
    
  3. Copy the code into a file named parse_csv.go.
  4. Run the program using the command:
                    go run parse_csv.go
    
  5. Observe the parsed CSV contents displayed in the terminal.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)