猿问

同时创建并写入两个 CSV golang

我正在尝试创建两个 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()

}


Helenr
浏览 123回答 1
1回答

慕妹3146593

在您的init函数中,您有两个写入者都写入成功文件。csvWriterSuccess = csv.NewWriter(csvSuccess) csvWriterError = csv.NewWriter(csvSuccess)分别写入成功文件和错误文件。csvWriterSuccess = csv.NewWriter(csvSuccess) csvWriterError = csv.NewWriter(csvError)
随时随地看视频慕课网APP

相关分类

Go
我要回答