Simple Go program to parse CSV files and print data in aligned tabular format on console with error handling and no external dependencies.
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
}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