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:
- Import necessary packages: The program uses
encoding/csv
for parsing CSV files andos
for file operations. - Open the CSV file: The program opens a file named
data.csv
. Ensure this file exists in the same directory as the program. - Create a CSV reader: A CSV reader is created to read the file contents.
- Read all rows: The program reads all rows from the CSV file using
reader.ReadAll()
. Each row is stored as a slice of strings. - Print the rows: The rows are iterated over, and each row is printed with its index.
How to Run
- Install Go from the official Go website.
- 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
- Copy the code into a file named
parse_csv.go
. - Run the program using the command:
go run parse_csv.go
- Observe the parsed CSV contents displayed in the terminal.