Home · RSS · E-Mail · GitHub · GitLab · Twitter

Working with CSV datasets in Go

See the repository for the current version!

Installation

go get -u github.com/sj14/csvutil

Examples

For all options please check the godoc. The examples ignore all error handling!


Create a new dataset

All datasets should contain a header for further processing.

records := [][]string{
    {"first_name", "last_name", "username"},
    {"Rob", "Pike", "rob"},
    {"Ken", "Thompson", "ken"},
    {"Robert", "Griesemer", "gri"},
}

ds := csvutil.New(records)

Add a new row

ds.AddRow([]string{"my first name", "my last name", "my nick"})
first_name,last_name,username
Rob,Pike,rob
Ken,Thompson,ken
Robert,Griesemer,gri
my first name,my last name,my nick

Add multiple rows

ds.AddRows([][]string{
    {"my first name 0", "my last name 0", "my nick 0"},
    {"my first name 1", "my last name 1", "my nick 1"},
    {"my first name 2", "my last name 2", "my nick 2"},
})
first_name,last_name,username
Rob,Pike,rob
Ken,Thompson,ken
Robert,Griesemer,gri
my first name 0,my last name 0,my nick 0
my first name 1,my last name 1,my nick 1
my first name 2,my last name 2,my nick 2

Add a new column at index 1

ds.AddCol([]string{"column_headline", "my row 1", "my row 2", "my row 3"}, 1)
ds.Write(os.Stdout)
first_name,column_headline,last_name,username
Rob,my row 1,Pike,rob
Ken,my row 2,Thompson,ken
Robert,my row 3,Griesemer,gri

Extract Column

lastNames, _ := ds.ExtractCol("last_name")
fmt.Println(lastNames)
[last_name Pike Thompson Griesemer]

Rename Column

ds.RenameCol("username", "nick")
first_name,last_name,nick
Rob,Pike,rob
Ken,Thompson,ken
Robert,Griesemer,gri

Delete Column

ds.DeleteCol("first_name")
last_name,nick
Pike,rob
Thompson,ken
Griesemer,gri

Modify Column

addRowNumber := func(val string, i int) string { return fmt.Sprintf("%v (%v)", val, i) }
ds.ModifyCol("first_name", addRowNumber)
ds.Write(os.Stdout)
first_name,last_name,username
Rob (1),Pike,rob
Ken (2),Thompson,ken
Robert (3),Griesemer,gri

Write the dataset

ds.Write(os.Stdout)
first_name,last_name,username
Rob,Pike,rob
Ken,Thompson,ken
Robert,Griesemer,gri

Write options

ds.Write(os.Stdout, csvutil.Delimiter('|'), csvutil.UseCLRF(true))
first_name|last_name|username
Rob|Pike|rob
Ken|Thompson|ken
Robert|Griesemer|gri

Get dataset as [][]string

fmt.Println(ds.Raw())
[[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]

Compare two (raw) datasets

a := [][]string{
    {"a", "b", "c"},
    {"d", "e", "f"},
}

b := [][]string{
    {"g", "h", "i"},
    {"j", "k", "l"},
}

result := csvutil.Equals(a, b)
fmt.Println(result)
false

Home · RSS · E-Mail · GitHub · GitLab · Twitter