LoginSignup
15
5

More than 3 years have passed since last update.

golangでcsvファイルを読み込みたい時

Last updated at Posted at 2019-02-03

備忘録として

os + encoding/csv モジュールを使う

foo.go
package main

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

func main() {
    file, err := os.Open("csvpath")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    reader := csv.NewReader(file)
    var line []string

    for {
        line, err = reader.Read()
        if err != nil {
            break
        }
        fmt.Println(line)
    }
}

reader.Read()は呼び出す度に一行ずつ取り出し、列毎に区切られた文字列のスライスを返すメソッド
そして全てのデータを取り出した後に呼び出すとerrorを返す仕組みである。
ここではforを無限ループさせて、errorを返したらbreakしている。
ちなみにerrorを返した場合のもう片方の値は空の文字列スライスになる

追記
エゴサしてたら参考としてこの記事が張られてました。
返すエラーは2種類であり、列が足りてないと別のエラーを吐くので気を付けましょうというお話です。
https://infraya.work/posts/go_csv_read/

15
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
5