3
1

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ファイルにレコードを追加する

Last updated at Posted at 2019-07-24

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

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?