DEV Community

made suande
made suande

Posted on

Read .CSV to get value

Read .CSV file by golang.

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strings"
)

func main() {
    f, err := os.Open("teksfile.csv")

    if err != nil {
        log.Fatal(err)
    }

    line_list := []string{}

    defer f.Close()
    scanner := bufio.NewScanner(f)
    i := 1
    for scanner.Scan() {
        if i == 1 {
            i = 0
            continue
        }
        line := scanner.Text()
        line_list = append(line_list, line)
    }
    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
    for _, ln := range line_list {
        row := strings.Split(ln, ":")
        debit   := row[0]
        credit  := row[1]
        db_acct := row[2]
        cr_acct := row[3]
        date    := row[4]

        fmt.Println(debit)
        fmt.Println(credit)
        fmt.Println(db_acct)
        fmt.Println(cr_acct)
        fmt.Println(date)
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

10
-10
12345678
12345679
20231210
Enter fullscreen mode Exit fullscreen mode

Top comments (0)