gpt4 book ai didi

csv - 同时创建和写入两个CSV golang

转载 作者:行者123 更新时间:2023-12-01 22:26:43 26 4
gpt4 key购买 nike

我正在尝试创建两个CSV文件并同时写入两者。这段代码不能那样工作,而只是为了说明我想做的事情。由于(* csv.Writer)是一个指针,所以我不知道如何将其与另一个文件区分开。有可能这样做吗?


package test

import (
"encoding/csv"
"os"
"sync"
"time"
)

var csvSuccess *os.File
var csvError *os.File
var csvErr error
var csvWriterSuccess *csv.Writer
var csvWriterError *csv.Writer
var mutex *sync.Mutex

func init() {
csvSuccess, csvErr = os.Create("sucess-result.csv")
csvError, csvErr = os.Create("error-result.csv")
if csvErr != nil {
panic("Error open file")
}
csvWriterSuccess = csv.NewWriter(csvSuccess)
csvWriterError = csv.NewWriter(csvSuccess)
mutex = &sync.Mutex{}
}

func WriteRecordSuccess(record []string) {
mutex.Lock()
if err := csvWriterSuccess.Write(record); err != nil {
if err != nil {
panic("Error writing success record")
}
csvWriterSuccess.Flush()
}
mutex.Unlock()
}

func WriteRecordError(record []string) {
mutex.Lock()
if err := csvWriterError.Write(record); err != nil {
if err != nil {
panic("Error writing error record")
}
csvWriterError.Flush()
}
mutex.Unlock()
}

func ClosecsvFile() {
csvWriterSuccess.Flush()
csvWriterError.Flush()
csvSuccess.Sync()
csvError.Sync()
csvSuccess.Close()
csvError.Close()
}

最佳答案

init函数中,两位作者都写入成功文件。

csvWriterSuccess = csv.NewWriter(csvSuccess)
csvWriterError = csv.NewWriter(csvSuccess)

分别写入成功和错误文件。
csvWriterSuccess = csv.NewWriter(csvSuccess)
csvWriterError = csv.NewWriter(csvError)

关于csv - 同时创建和写入两个CSV golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59531388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com