2

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 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Woops! And in the context of my problem that made so much sense.
@mr0il Just remember what I said about Error. I didn't include it in the deferred function call, but that doesn't mean it's not important. Imagine that while you were writing to the writer's buffer, another process changed the permissions or owner of the file. That means when you call Flush, you might suddenly be unable to write to the file. While you can rarely do anything about it, such as trying again, you can at least log the issue and refer users to the log file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.