英文:
Golang, writing csv file result file sometimes empty
问题
我正在处理一个解析表,并决定以可读的格式查看该表。当我使用一个大型语法创建CSV文件时,它成功输出结果。然而,解析表是不正确的。所以,我试图用一个更简单的语法进行测试。出于某种原因,这段代码会生成一个带有大型语法的CSV文件,但是对于简单的语法,文件是空白的。我在这里做错了什么?
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)
}
}
你在这里做错了什么取决于你的具体问题。但是,根据你提供的代码,有几个可能的问题:
-
检查
TerminalSymbolList
和ParseTable
是否包含正确的数据。确保它们不是空的,并且包含你期望的值。 -
检查
UnionSlices
函数的实现。确保它正确地合并了tsl
和TerminalSymbolList
。 -
检查文件路径和文件名是否正确。确保你有权限创建和写入文件。
-
检查
Check
函数的实现。它可能会引发错误,导致文件无法正确创建或写入。
请逐个检查这些问题,并确保代码中没有其他潜在的错误。如果问题仍然存在,请提供更多的上下文和错误信息,以便我可以更好地帮助你解决问题。
英文:
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
得分: 7
你需要调用CSV写入器的Flush
方法,确保所有缓冲的数据在关闭文件之前都被写入文件中。你可以使用以下修改:
f, err := os.Create("tableFile3.csv")
Check(err)
w := csv.NewWriter(f)
defer func() {
w.Flush()
f.Close()
}()
这个概念可以扩展到所有使用缓冲区的写入器。
奇怪的是,Flush
方法不返回任何内容,与*bufio.Writer
的Flush
方法返回的error
不同,但你可以使用Error
方法检查在前面的Write
或Flush
调用期间可能发生的错误。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论