我正在尝试创建两个 CSV 文件并同时写入。这段代码不是这样工作的,但它只是为了举例说明我想要做的事情。由于 (* csv.Writer) 是一个指针,我不知道如何将它与另一个文件区分开。可以这样做吗?package testimport ( "encoding/csv" "os" "sync" "time")var csvSuccess *os.Filevar csvError *os.Filevar csvErr errorvar csvWriterSuccess *csv.Writervar csvWriterError *csv.Writervar mutex *sync.Mutexfunc 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()}
1 回答
慕妹3146593
TA贡献1820条经验 获得超9个赞
在您的init
函数中,您有两个写入者都写入成功文件。
csvWriterSuccess = csv.NewWriter(csvSuccess) csvWriterError = csv.NewWriter(csvSuccess)
分别写入成功文件和错误文件。
csvWriterSuccess = csv.NewWriter(csvSuccess) csvWriterError = csv.NewWriter(csvError)
- 1 回答
- 0 关注
- 121 浏览
添加回答
举报
0/150
提交
取消