当在通道上迭代时,使用Go文件IO写入操作失败。

huangapple go评论88阅读模式
英文:

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 (
	&quot;encoding/csv&quot;
	&quot;log&quot;
	&quot;os&quot;
)

func main() {
	file, err := os.Create(&quot;test.csv&quot;)
	if err != nil {
		log.Fatalf(&quot;Error opening file: %s&quot;, err.Error())
	}
	defer file.Close()

	writer := csv.NewWriter(file)
	channel := make(chan []string)
	counter := 0

	go func() {
		defer close(channel)

		for i := 0; i &lt; 100; i++ {
			channel &lt;- []string{&quot;col1&quot;, &quot;col2&quot;}
		}
	}()

	for vals := range channel {
		if err := writer.Write(vals); err != nil {
			log.Fatalf(&quot;Error writing to csv: %s&quot;, err.Error())
		}
		counter++
	}

	log.Printf(&quot;%d lines written&quot;, 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()

更多信息请参考这里

英文:

You are missing writer.Flush() at the end of your function.

More info here

huangapple
  • 本文由 发表于 2015年12月3日 12:15:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/34057795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定