to be
a problem slover

go write csv to file

package main

import (
    "encoding/csv"
    "log"
    "os"
)

func main() {
    rows := [][]string{
        {"Name", "City", "Language"},
        {"Pinky", "London", "Python"},
        {"Nicky", "Paris", "Golang"},
        {"Micky", "Tokyo", "Php"},
    }

    csvfile, err := os.Create("test.csv")
    defer func() {
        csvWriter.Flush()
        _ = csvFile.Close()
    }()
    if err != nil {
        log.Fatalf("failed creating file: %s", err)
    }

    csvwriter := csv.NewWriter(csvfile)

    for _, row := range rows {
        _ = csvwriter.Write(row) // if write concurrently, use sync.Mutex for lock & write
    }
}

context

sometimes I need to log struct data, but don’t want to use db, so csv is a lightweight choose.

reference

Golang write CSV records

赞(2) 打赏
欢迎转载,注明出处:刘世明的博客 » go write csv to file

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下作者

支付宝扫一扫打赏

微信扫一扫打赏