Help us understand the problem. What is going on with this article?

Go言語でCSVの読み書き(sjis、euc、utf8対応)

More than 3 years have passed since last update.

Go言語でCSVファイルの読み書き

このサンプルで詰まっている要素

  • CSVファイル入出力(CRLF、デリミタ指定)
  • 文字コード変換
  • 引数
  • ログ出力
  • スライス処理
  • 数値→文字列変換

カラムが2つ以上あるsjisなcsvファイルを用意してください。

csv.go
/*
GOROOT、GOPATHの設定を忘れずに
例) GOROOT=c:\tools\go
    GOPATH=c:\tools\go
    PATH=c:\tools\go\bin

最初にパッケージのダウンロードとインストール
c:\>go version
go version go1.4.2 windows/amd64

go get golang.org/x/text/encoding/japanese
go get golang.org/x/text/transform

go run csv.go "入力ファイル.csv" "出力ファイル名.csv"
go build csv.go 
*/
package main

import (
    "golang.org/x/text/encoding/japanese"
    "golang.org/x/text/transform"
    "encoding/csv"
    "io"
    "flag"
    "log"
    "os"
    "fmt"
)

func failOnError(err error) {
    if err != nil {
        log.Fatal("Error:", err)
    }
}

func main() {
    flag.Parse()

    //読み込みファイル準備
    file1, err := os.Open(flag.Arg(0))
    failOnError(err)
    defer file1.Close()

    //書き込みファイル準備
    file2, err := os.Create(flag.Arg(1))
    failOnError(err)
    defer file2.Close()

    reader := csv.NewReader(transform.NewReader(file1, japanese.ShiftJIS.NewDecoder()))
//  reader := csv.NewReader(transform.NewReader(file1, japanese.EUCJP.NewDecoder()))
//  reader := csv.NewReader(file1) //utf8
    reader.LazyQuotes = true // ダブルクオートを厳密にチェックしない

    writer := csv.NewWriter(transform.NewWriter(file2, japanese.ShiftJIS.NewEncoder()))
//  writer := csv.NewWriter(transform.NewWriter(file2, japanese.EUCJP.NewEncoder()))
//  writer := csv.NewWriter(file2) //utf8
    writer.UseCRLF = true //デフォルトはLFのみ
//  writer.Comma = '\t'

    log.Printf("Start")
    for {
        record, err := reader.Read() // 1行読み出す
        if err == io.EOF {
            break
        } else {
            failOnError(err)
        }
        var new_record []string
        for i, v := range record {
            if i > 0 {
                new_record = append(new_record, fmt.Sprint(i) + ":" + v)
            }
        }
        writer.Write(new_record) // 1行書き出す
//      log.Printf("%#v", record[0] + "," + record[1])
    }
    writer.Flush()
    log.Printf("Finish !")
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした