英文:
Write function from encoding/csv pkg stops writting in csv file
问题
我正在尝试提取文件夹中的.txt文件的名称。
但是我遇到了一个问题,即来自encoding/csv的写入函数停止写入我初始化的csv文件。
以下是代码:
import (
"encoding/csv"
"io/ioutil"
"log"
"os"
"strings"
)
func Extract() error {
//读取文件夹
AllFiles, err := ioutil.ReadDir("./folder")
if err != nil {
return err
}
//创建csv文件
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)
//写入csv文件
err = WriterSupport.Write(res)
if err != nil {
return err
}
}
return nil
}
我在文件夹中有大约300个.txt文件。
log.Println打印了所有内容,所以问题必须出在Write函数上。
返回的csv文件中少了一些文件名,并且最后一个文件名没有完全写入。
此外,当我更改res中"test"字符串的字母数量时,返回的csv文件中的文件名数量也会增加或减少。
Write函数没有返回错误。
英文:
I'm trying to extract the names of .txt files in a folder.<br />
But I encounter an issue where the write function from encoding/csv stop writing in the csv file I initialize.<br />
The code is as follow.<br />
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.<br />
The log.Println prints everything so the issue must be with the Write function.<br />
In return the csv file as less file name and the last name is not written entirely.<br />
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.<br />
Write returns no error.
答案1
得分: 3
看起来你在写入后错过了WriterSupport.Flush()。你只需要将Flush()延迟执行,以确保它被执行。最好在创建WriterSupport := csv.NewWriter(SupportCsv)
之后添加延迟。
WriterSupport := csv.NewWriter(SupportCsv)
defer WriterSupport.Flush()
英文:
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)
<!--- language:go --->
WriterSupport := csv.NewWriter(SupportCsv)
defer WriterSupport.Flush()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论