dongmiyi8220 2017-04-29 21:18
浏览 415
已采纳

Golang,写入csv文件结果文件有时为空

I'm working on a parsetable and decided I'd like to see the table in a readable format. When I created the csv with a large grammar, it successfully outputs the results. However, the parse table isn't correct. So, I'm trying to test with a more simple grammar. For some reason this code produces a csv file with my large grammar, but with the simple grammar the file is blank. What am I doing wrong here?

func WriteTableToFile() {
    f, err := os.Create("tableFile3.csv")
    Check(err)
    defer f.Close()
    w := csv.NewWriter(f)
    var tsl []string
    tsl = append(tsl, " ")
    tsl, _ = UnionSlices(tsl, TerminalSymbolList)
    w.Write(tsl)
    fmt.Println(tsl)

    for ntk := range ParseTable {
        var writeSlice []string
        writeSlice = append(writeSlice, ntk)
        for _, tk := range TerminalSymbolList {
            for _, p := range ParseTable[ntk][tk] {
                writeSlice = append(writeSlice, p)
                fmt.Println("appending ", p)
            }
        }
        w.Write(writeSlice)
        fmt.Println("wrote ", writeSlice)
    }
}
  • 写回答

1条回答 默认 最新

  • doudiecai1572 2017-04-29 21:43
    关注

    You need to call the Flush method of your CSV writer to ensure all buffered data is written to your file before closing the file. You can use the following modification:

    f, err := os.Create("tableFile3.csv")
    Check(err)
    w := csv.NewWriter(f)
    defer func() {
        w.Flush()
        f.Close()
    }()
    

    This concept can be extended to apply to all writers that use buffers.

    Oddly enough, the Flush method doesn't return anything, unlike the error returned by the Flush method of a *bufio.Writer but you can use the Error method to check for errors that might have occurred during a preceding Write or Flush call.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格