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

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)
    }
}

图片转代码服务由CSDN问答提供 功能建议

我正在研究可解析的对象,并决定我希望以可读格式查看表格。 当我使用较大的语法创建csv时,它会成功输出结果。 但是,解析表不正确。 因此,我正在尝试使用更简单的语法进行测试。 出于某种原因,此代码会生成一个包含我大语法的csv文件,但使用简单语法,该文件为空白。 我在这里做什么错了?

  func WriteTableToFile(){
f,err:= os.Create(“ tableFile3.csv”)
 Check(err)
 延迟f.Close()
w:= csv.NewWriter(f)
 var tsl [] string 
 tsl = append(tsl,“”)
 tsl,_ = UnionSlices(tsl,TerminalSymbolList)
 w。  ntk的write(tsl)
 fmt.Println(tsl)
 
:=范围ParseTable {
 var writeSlice [] string 
 writeSlice = append(writeSlice,ntk)
表示_,tk:=范围TerminalSymbolList  {
表示_,p:=范围ParseTable [ntk] [tk] {
 writeSlice = append(writeSlice,p)
 fmt.Println(“ append”,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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题