66
65

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言語でCSVの読み書き(sjis、euc、utf8対応)

Last updated at Posted at 2015-08-11

#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 !")
}
66
65
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
66
65

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?