简体   繁体   English

通过通道迭代写入时,Go文件IO失败

[英]Go file IO fails when writing while iterating over a channel

I'm having an issue with writing lines to a csv file while iterating over a channel. 我在遍历通道时将行写入csv文件时遇到问题。 I'm new to Go, but the syntax for file IO looks synchronous to me. 我是Go的新手,但是文件IO的语法对我来说似乎是同步的。 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. 有一个go例程通过通道传递值,我正在遍历这些值并将它们写入CSV文件。 I get no errors, and at the end it logs that 100 lines have been written. 我没有收到任何错误,最后记录了已写入100行。

When I check the CSV file though it's empty. 当我检查CSV文件时,尽管它是空的。 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. 您在函数末尾缺少writer.Flush()

More info here 更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM