我正在尝试创建两个 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()
}
慕妹3146593
相关分类