Monday, April 22, 2024
HomeGolangLearn a CSV file in Go (Golang)

Learn a CSV file in Go (Golang)



To simply learn and parse CSV (or TSV) information in Go, you should use two strategies of encoding/csv package deal:

See additionally our instance of methods to write information to a CSV file in Go

Within the examples beneath, we use information.csv file:

greens,fruits
carrot,banana
potato,strawberry

Learn all the CSV file directly

On this instance, we open the CSV file, initialize csv.Reader and browse all the information right into a [][]string slice the place the primary index is the file’s line quantity and the second is an index of the comma-separated worth on this line. We are able to do one thing with these information, for instance, convert to an array of structs.

package deal fundamental

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

kind ShoppingRecord struct {
    Vegetable string
    Fruit     string
}

func createShoppingList(information [][]string) []ShoppingRecord {
    var shoppingList []ShoppingRecord
    for i, line := vary information {
        if i > 0 { // omit header line
            var rec ShoppingRecord
            for j, discipline := vary line {
                if j == 0 {
                    rec.Vegetable = discipline
                } else if j == 1 {
                    rec.Fruit = discipline
                }
            }
            shoppingList = append(shoppingList, rec)
        }
    }
    return shoppingList
}

func fundamental() {
    // open file
    f, err := os.Open("information.csv")
    if err != nil {
        log.Deadly(err)
    }

    // keep in mind to shut the file on the finish of this system
    defer f.Shut()

    // learn csv values utilizing csv.Reader
    csvReader := csv.NewReader(f)
    information, err := csvReader.ReadAll()
    if err != nil {
        log.Deadly(err)
    }

    // convert information to array of structs
    shoppingList := createShoppingList(information)

    // print the array
    fmt.Printf("%+vn", shoppingList)
}

Output:

[{Vegetable:carrot Fruit:banana} {Vegetable:potato Fruit:strawberry}]

Learn a CSV file line by line

Studying line by line is much like studying the entire file directly, however on this case, we use csv.Reader.Learn() methodology to learn the subsequent line of information within the infinite loop. This loop is exited when no extra information can be found, i.e., io.EOF error happens.

package deal fundamental

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

func fundamental() {
    // open file
    f, err := os.Open("information.csv")
    if err != nil {
        log.Deadly(err)
    }

    // keep in mind to shut the file on the finish of this system
    defer f.Shut()

    // learn csv values utilizing csv.Reader
    csvReader := csv.NewReader(f)
    for {
        rec, err := csvReader.Learn()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Deadly(err)
        }
        // do one thing with learn line
        fmt.Printf("%+vn", rec)
    }
}

Output:

[vegetables fruits]
[carrot banana]
[potato strawberry]

Use a non-default discipline delimiter and browse a TSV file

The usual separator for csv.Reader is the comma, nevertheless it’s straightforward to alter it to any rune. As an example, you’ll be able to change it to the tab character t, and on this approach, you get the TSV reader:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments