encording/csv パッケージを使うことで、Goで CSVを簡単に扱うことができます。
レコード追加方法でつまづいたのでメモ。
main.go
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
// ファイルがある場合はレコード追加、ない場合はファイル作成される
file, err := os.OpenFile("/tmp/export.csv", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal("Error:", err)
}
defer file.Close()
// 追加するレコードはstringのスライスで定義
record := []string{"hoge", "fuga"}
writer := csv.NewWriter(file)
err = writer.Write(record)
if err != nil {
log.Fatal("Error:", err)
}
writer.Flush()
}
export.csv(上記のプログラムを2回実行した結果)
hoge,fuga
hoge,fuga