CSV File Parser and Tabular Print in Go

Simple Go program to parse CSV files and print data in aligned tabular format on console with error handling and no external dependencies.

Brief Introduction

CSV File Parser and Tabular Print in Go (go)
DESCRIPTION:
A simple Go program that reads a CSV file, parses it, and prints the data in a tabular format on the console. Useful for quickly viewing CSV contents without external dependencies.

ADDITIONAL NOTES:
The program handles file opening and CSV parsing errors. It prints data in a table with aligned columns. It does not support CSVs with multiline cells or separators other than commas.

EXPLANATIONS:
- Uses the 'encoding/csv' package to easily read CSV files without writing a manual parser.
- Calculates the maximum width of each column to align tabular printing in the console.
- Handles errors to avoid crashes in case of missing files or malformed data.
- Prints a separator row to improve table readability.

Example Code: go

package main

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

func main() {
	// CSV file name to read
	fileName := "data.csv"

	// Opening the file
	file, err := os.Open(fileName)
	if err != nil {
		fmt.Printf("Error opening file %s: %v\n", fileName, err)
		return
	}
	defer file.Close()

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

	// Reading all rows
	records, err := reader.ReadAll()
	if err != nil {
		fmt.Printf("Error reading CSV: %v\n", err)
		return
	}

	if len(records) == 0 {
		fmt.Println("The CSV file is empty.")
		return
	}

	// Calculating the maximum width for each column
	colWidths := make([]int, len(records[0]))
	for _, row := range records {
		for i, cell := range row {
			if len(cell) > colWidths[i] {
				colWidths[i] = len(cell)
			}
		}
	}

	// Function to print a separator row
	printSeparator := func() {
		for _, w := range colWidths {
			fmt.Print("+", stringRepeat("-", w+2))
		}
		fmt.Println("+")
	}

	// Printing the header (first row)
	printSeparator()
	printRow(records[0], colWidths)
	printSeparator()

	// Printing the following rows
	for _, row := range records[1:] {
		printRow(row, colWidths)
	}
	printSeparator()
}

// Helper function to print a row with padding
func printRow(row []string, widths []int) {
	for i, cell := range row {
		fmt.Printf("| %-*s ", widths[i], cell) // %-*s = left alignment with width
	}
	fmt.Println("|")
}

// Helper function to repeat a string n times
func stringRepeat(s string, count int) string {
	result := ""
	for i := 0; i < count; i++ {
		result += s
	}
	return result
}
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Go runtime (version 1.13+ recommended)

Input CSV file (example: data.csv)

DEPENDENCIES: standard package 'encoding/csv' for CSV parsing

DEPENDENCIES: standard package 'os' for file handling

DEPENDENCIES: standard package 'fmt' for formatted output

CONFIG: the CSV file must be in the same folder as the program or specify the correct path

Similar Topics