使用范围循环迭代时,问题写入CSV文件的条目
在此代码中,我试图在目录中读取书名,然后将其写入CSV文件中,但它仅在CSV文件中写下第一个书名。我不知道如何使其进一步运作。
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()
}
}
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()
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于您将关闭循环内的文件,因此在第一次迭代之后,它已经关闭。另外,无需在循环中创建
csvwriter
,您可以在循环后创建并冲洗它。请注意,您可以使用 defer语句设置文件句柄和作者的清理代码在创建它们之后(通过这种方式,您不必担心在控制流程可能从功能中返回的任何地方明确包含清理代码)。在离开函数之前,将以反顺序执行延期语句,因此在csvwriter.flush()
下面的示例中,将在csvfile.close.close()
之前执行预期的: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 belowcsvWriter.Flush()
will be executed beforecsvFile.Close()
, as expected: