1

I'm trying to extract the names of .txt files in a folder.
But I encounter an issue where the write function from encoding/csv stop writing in the csv file I initialize.
The code is as follow.

import (
        "encoding/csv"
        "io/ioutil"
        "log"
        "os"
        "strings"
)

func Extract() error {

    //read folder
    AllFiles, err := ioutil.ReadDir("./folder")
    if err != nil {
        return err
    }

    //create csv file
    SupportCsv, err := os.Create("csvfile.csv")
    if err != nil {
        return err
    }

    WriterSupport := csv.NewWriter(SupportCsv)

    for _, file := range AllFiles {

        res := []string{"test", file.Name()}

        log.Println(res)

        //write in csv file
        err = WriterSupport.Write(res)
        if err != nil {
            return err
        }
    }
return nil
}

I have ~300 .txt file in my folder.
The log.Println prints everything so the issue must be with the Write function.
In return the csv file as less file name and the last name is not written entirely.
Moreover, when i change the number of letter on "test" string in res, the csv file as in return more or less file name in it.
Write returns no error.

3
  • => pkg.go.dev/encoding/csv#Writer.Flush Commented Jul 23, 2021 at 10:10
  • 1
    Also, don't forget to close your file: defer SupportCsv.Close(). Commented Jul 23, 2021 at 10:11
  • Thank you @jub0bs everything works find now Commented Jul 23, 2021 at 10:21

1 Answer 1

3

Looks like you have missed WriterSupport.Flush() after the write. All you need to do is to defer the Flush() to make sure that it is executed. Better after creating WriterSupport := csv.NewWriter(SupportCsv)

WriterSupport := csv.NewWriter(SupportCsv)
defer WriterSupport.Flush()
Sign up to request clarification or add additional context in comments.

2 Comments

No, flushing within the loop most likely isn't what you want. Do it once after of the loop. Better yet: defer WriterSupport.Flush() after creating the writer.
@jub0bs I agree that the flushing within loop is not the right way of doing this. Updated the answer.

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.