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?
You are missing writer.Flush()
at the end of your function.
More info here