In this code, I am trying to read the book titles in a directory and then write them in a CSV file but it is writing only the first book title in a CSV file. I don't know how to make it work further.
package main
import (
"encoding/csv"
"io/ioutil"
"log"
"os"
)
func main() {
files, err := ioutil.ReadDir("/home/bilal/Documents/Books/English")
if err != nil {
log.Fatal(err)
}
csvFile, err := os.Create("English.csv")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
// fmt.Println(file.Name())
fileData := []string{
file.Name(),
}
csvWriter := csv.NewWriter(csvFile)
csvWriter.Write(fileData)
csvWriter.Flush()
csvFile.Close()
}
}
CodePudding user response:
The problem is that you are closing the file inside the loop, so after the first iteration it's already closed. Also, there's no need to create csvWriter
inside a loop, you can create one and flush it after the loop. Note that you can use defer statements to set the cleanup code for both the file handle and the writer right after creating them (in this way, you don't have to worry about including cleanup code explicitly everywhere the control flow may return from the function). Before leaving the function, defer statements will be executed in the reverse order, so in the example below csvWriter.Flush()
will be executed before csvFile.Close()
, as expected:
// ...
csvFile, err := os.Create("English.csv")
if err != nil {
log.Fatal(err)
}
defer csvFile.Close()
csvWriter := csv.NewWriter(csvFile)
defer csvWriter.Flush()
for _, file := range files {
fileData := []string{ file.Name() }
csvWriter.Write(fileData)
}
// ...