使用范围循环迭代时,问题写入CSV文件的条目

发布于 2025-02-07 08:44:24 字数 678 浏览 0 评论 0原文

在此代码中,我试图在目录中读取书名,然后将其写入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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘东忘西忘不掉你 2025-02-14 08:44:24

问题在于您将关闭循环内的文件,因此在第一次迭代之后,它已经关闭。另外,无需在循环中创建csvwriter,您可以在循环后创建并冲洗它。请注意,您可以使用 defer语句设置文件句柄和作者的清理代码在创建它们之后(通过这种方式,您不必担心在控制流程可能从功能中返回的任何地方明确包含清理代码)。在离开函数之前,将以反顺序执行延期语句,因此在csvwriter.flush()下面的示例中,将在csvfile.close.close()之前执行预期的:

// ...
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)
}
// ...

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)
}
// ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文