英文:
Go file IO fails when writing while iterating over a channel
问题
我在使用通道迭代时遇到了向CSV文件写入行的问题。我对Go语言还不熟悉,但是文件IO的语法对我来说看起来是同步的。鉴于我期望写操作成功返回表示写入完成,但实际情况并非如此。以下是我应用程序中的基本情况:
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
file, err := os.Create("test.csv")
if err != nil {
log.Fatalf("Error opening file: %s", err.Error())
}
defer file.Close()
writer := csv.NewWriter(file)
channel := make(chan []string)
counter := 0
go func() {
defer close(channel)
for i := 0; i < 100; i++ {
channel <- []string{"col1", "col2"}
}
}()
for vals := range channel {
if err := writer.Write(vals); err != nil {
log.Fatalf("Error writing to csv: %s", err.Error())
}
counter++
}
log.Printf("%d lines written", counter)
}
有一个Go协程通过通道传递值,我正在迭代这些值并将它们写入CSV文件。我没有收到任何错误,并且最后记录说已经写入了100行。
然而,当我检查CSV文件时,发现它是空的。我在应用程序中观察到的行为是文件被不完整地写入;它会在写入记录的一半时停止。我确定我漏掉了一些东西,但是如果写入没有错误,为什么文件中没有任何内容呢?
英文:
I'm having an issue with writing lines to a csv file while iterating over a channel. I'm new to Go, but the syntax for file IO looks synchronous to me. Given that I would expect that a write operation returning successfully would indicate that the write is complete, but that's not what I'm observing. This is essentially what I have going on in my application:
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
file, err := os.Create("test.csv")
if err != nil {
log.Fatalf("Error opening file: %s", err.Error())
}
defer file.Close()
writer := csv.NewWriter(file)
channel := make(chan []string)
counter := 0
go func() {
defer close(channel)
for i := 0; i < 100; i++ {
channel <- []string{"col1", "col2"}
}
}()
for vals := range channel {
if err := writer.Write(vals); err != nil {
log.Fatalf("Error writing to csv: %s", err.Error())
}
counter++
}
log.Printf("%d lines written", counter)
}
There's a go routine passing values through a channel, and I'm iterating over those values and writing them to a CSV file. I get no errors, and at the end it logs that 100 lines have been written.
When I check the CSV file though it's empty. The behavior I'm seeing in my application is the file is written incompletely; it'll stop halfway through writing a record. I'm sure I'm missing something, but if the write returns with no errors why is there nothing in the file?
答案1
得分: 3
你的函数末尾缺少 writer.Flush()
。
更多信息请参考这里。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论