21
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go で euc-jp や sjis の csv ファイルを読み込むには変換用のリーダーを1つかませるだけでよかった

Last updated at Posted at 2014-06-12

概要

csvファイルがutf8で書かれてなかったのでgoだけで出来ないか調べてみたメモ.
# iconvとかで元ファイルを前処理してから読めばそれでいい気もします・・・.

関連:

準備

以下のパッケージを利用しました.利用方法などはこちらを参照ください.

"code.google.com/p/go.text/encoding/japanese"
"code.google.com/p/go.text/transform"

サンプルコード

文字コードがeuc-jpの場合のサンプルです.sjisの場合は★のところを
japanese.ShiftJIS.NewDecoder()に変更すれば対応できます.

文字コード変換をかませるだけなので,別にcsvの読み込みじゃなくても汎用的に利用できそうです.

package main

import (
        "code.google.com/p/go.text/encoding/japanese"
        "code.google.com/p/go.text/transform"
        "encoding/csv"
        "fmt"
        "io"
        "os"
)

func main() {

        var fp *os.File
        if len(os.Args) < 2 {
                fp = os.Stdin
        } else {
                var err error
                fp, err = os.Open(os.Args[1])
                if err != nil {
                        panic(err)
                }
                defer fp.Close()
        }

        reader := csv.NewReader(transform.NewReader(fp, japanese.EUCJP.NewDecoder())) // ←★
        for {
                record, err := reader.Read()
                if err == io.EOF {
                        break
                } else if err != nil {
                        panic(err)
                }
                fmt.Println(record)
        }
}
21
21
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
21
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?