GoCsv is a library written in pure Go to use csv data more comfortable

GoCsv

GoCsv is a library written in pure Go to use csv data more comfortable

Supported Go version

  • golang >= 1.13

Installation

go get github.com/shr0048/gocsv

Feature

  • Freely set the separator (Ex: ',' '\t' ';' etc)
  • Support Collection model
  • Include Map, Filter, Reduce
  • All cell data is converting Go-Map

Example

= 21 { return true } else { return false } } } // No 'Age' Column return false } func totalAge(a, b interface{}) interface{} { var age float64 for _, cell := range b.(gocsv.Record) { if val, ok := cell[`"Age"`]; ok { age, _ = strconv.ParseFloat(strings.TrimSpace(val), 64) } } return a.(float64) + age } func main() { fmt.Println("##### Example of Using Collection functions #####") myCsv := gocsv.CSV{} err := myCsv.LoadCSV("./mlb_players.csv", ", ") if err != nil { fmt.Print("Load error") } fmt.Println("Convert all Name as uppercase") // Apply Map mapCsv := myCsv.Map(convertCap) // Print all rows row, ok := mapCsv.NextRow() for ok { fmt.Println(row) row, ok = mapCsv.NextRow() } // Apply Filter and Reduce filtered := mapCsv.Filter(filteringAge) count := filtered.RowNum avg := filtered.Reduce(float64(0), totalAge) fmt.Printf("Get average age over 21: %f \n", avg.(float64) / float64(count)) } ">
package main

import (
	"fmt"
	"github.com/shr0048/gocsv"
	"strconv"
	"strings"
)

func convertCap(record gocsv.Record) gocsv.Record {
	newRecod := gocsv.Record{}
	for _, cell := range record {
		if val, ok := cell[`"Name"`]; ok {
			capVal := strings.ToUpper(val)
			newCell := gocsv.Cell{"Name": capVal}

			newRecod = append(newRecod, newCell)
		} else {
			newRecod = append(newRecod, cell)
		}
	}
	return newRecod
}

func filteringAge(record gocsv.Record) bool {
	for _, cell := range record {
		if val, ok := cell[`"Age"`]; ok {
			age, _ := strconv.ParseFloat(strings.TrimSpace(val), 64)
			if age >= 21 {
				return true
			} else {
				return false
			}
		}
	}
	// No 'Age' Column
	return false
}

func totalAge(a, b interface{}) interface{} {
	var age float64
	for _, cell := range b.(gocsv.Record) {
		if val, ok := cell[`"Age"`]; ok {
			age, _ = strconv.ParseFloat(strings.TrimSpace(val), 64)
		}
	}
	return a.(float64) + age
}

func main() {
	fmt.Println("##### Example of Using Collection functions #####")

	myCsv := gocsv.CSV{}
	err := myCsv.LoadCSV("./mlb_players.csv", ", ")
	if err != nil {
		fmt.Print("Load error")
	}

	fmt.Println("Convert all Name as uppercase")
	// Apply Map
	mapCsv := myCsv.Map(convertCap)
	// Print all rows
	row, ok := mapCsv.NextRow()
	for ok {
		fmt.Println(row)
		row, ok = mapCsv.NextRow()
	}

	// Apply Filter and Reduce
	filtered := mapCsv.Filter(filteringAge)
	count := filtered.RowNum
	avg := filtered.Reduce(float64(0), totalAge)

	fmt.Printf("Get average age over 21: %f \n", avg.(float64) / float64(count))
}

License

MIT License

Copyright (c) 2020 HeraldSim

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Contact

[email protected]

Similar Resources

Golang PDF library for creating and processing PDF files (pure go)

UniPDF - PDF for Go UniDoc UniPDF is a PDF library for Go (golang) with capabilities for creating and reading, processing PDF files. The library is wr

Dec 28, 2022

A simple library for generating PDF written in Go lang

gopdf gopdf is a simple library for generating PDF document written in Go lang. Features Unicode subfont embedding. (Chinese, Japanese, Korean, etc.)

Jan 3, 2023

goelftools is library written in Go for parsing ELF file.

goelftools goelftools is library written in Go for parsing ELF file. This library is inspired by pyelftools and rbelftools. Motivation The motivation

Dec 5, 2022

A blazingly-fast simple-to-use tool to find duplicate files on your computer, portable hard drives etc.

A fast and simple tool to find duplicate files (photos, videos, music, documents) on your computer, portable hard drives etc.

Jan 9, 2023

A virtual file system for small to medium sized datasets (MB or GB, not TB or PB). Like Docker, but for data.

AetherFS assists in the production, distribution, and replication of embedded databases and in-memory datasets. You can think of it like Docker, but f

Feb 9, 2022

An API for handling file meta data

dp-files-api An API for handling file meta data Getting started Run make debug Dependencies No further dependencies other than those defined in go.mod

Jan 4, 2022

Read data from rss, convert in pdf and send to kindle. Amazon automatically convert them in azw3.

Kindle-RSS-PDF-AZW3 The Kindle RSS PDF AZW3 is a personal project. The Kindle RSS PDF AZW3 is a personal project. I received a Kindle for Christmas, a

Jan 10, 2022

A PDF processor written in Go.

A PDF processor written in Go.

pdfcpu: a Go PDF processor pdfcpu is a PDF processing library written in Go supporting encryption. It provides both an API and a CLI. Supported are al

Jan 8, 2023
Related tags
csv reader/writer and csv generator.

IO csv reader sample version 0.0.1-SNAPSHOT Goals: main: read huge file, hex substring, write to new file. repo has 2 version. v1 can read a file and

Nov 4, 2021
gsheet is a CLI tool (and Golang package) for piping csv data to and from Google Sheets

gsheet Table of Contents Introduction Why? Installation Authentication and Authorization What about OAuth authentication? CLI Usage Sheet commands Dri

Nov 15, 2022
Read csv file from go using tags

go-csv-tag Read csv file from Go using tags The project is in maintenance mode. It is kept compatible with changes in the Go ecosystem but no new feat

Nov 16, 2022
Allows parsing CSV files into custom structs and implements required fields that can't be empty

Welcome to Go Custom CSV Parser ?? Allows parsing CSV files into custom structs and implements required fields that can't be empty ?? Homepage Install

Nov 9, 2021
A simple utility for validating CSV columns

gompare A simple utility for validating CSV columns Building In project directly, run go build Usage ./gompare --template-file=template.csv --input-fi

Feb 3, 2022
Simple go script that converts csv file into a json document

csv-go-parser Simple go script that converts csv file into a json document. CSV Input: id,first_name,last_name,email,avatar,ip_address 1,Pauline,Hirth

Jun 4, 2022
Extract profiles and tasks information from CSV file

Footsite-Bot ideas from jw6602 Extract profiles and tasks information from CSV f

Nov 25, 2022
This program let you create a DataSet (.CSV) with all TedTalks

TedTalks-Scraper This program let you create a file .CSV with all information from TedTalks, including: Title Description Views (Number of Views) Auth

Dec 26, 2021
CSV asynchronous I/O package for go.

golib/csvio selectでの非同期処理に対応した、csvベースでの読み込み/書き込みを行うライブラリです。 csvio.Config CSVのコンマの値や、クォートの有無など、扱うCSVに対するフォーマットを指定できます。 csvio.Reader selectでの非同期処理に対応した、

Jan 21, 2022
FujiSimuRecipesGen - A Golang program to generate Fujifilm simulations from recipes of such simulations in CSV

FujiSimuRecipesGen - A Golang program to generate Fujifilm simulations from recipes of such simulations in CSV

Aug 12, 2022