Skip to content

Instantly share code, notes, and snippets.

@sophistifunk
Created May 6, 2014 11:11
Show Gist options
  • Save sophistifunk/880c5de516c2e011c64e to your computer and use it in GitHub Desktop.
Save sophistifunk/880c5de516c2e011c64e to your computer and use it in GitHub Desktop.
package main
// Originally ripped from here: http://www.ostree.org/code-snippet/91/csv-comma-separated-values-example-in-golang and modified.
import (
"encoding/csv"
"fmt"
"os"
"unicode/utf8"
"strings"
)
func maxInt(a int, b int) int {
if a >= b {
return a
}
return b
}
func main() {
// Open file
file, err := os.Open("./some-file.csv")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
// Grab CSV data
reader := csv.NewReader(file)
allRows, err := reader.ReadAll()
if err != nil {
fmt.Println("Error:", err)
return
}
// Measure
var widths []int
for _, row := range allRows {
for colNum, value := range row {
if len(widths) < colNum+1 {
widths = append(widths, len(value))
} else {
widths[colNum] = maxInt(widths[colNum], utf8.RuneCountInString(value))
}
}
}
// Dump
for _, row := range allRows {
for colNum, value := range row {
fmt.Print("| " + value + " " + strings.Repeat(" ", widths[colNum]-utf8.RuneCountInString(value)+1))
}
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment