英文:
Write to csv in GO error
问题
我正在尝试使用GO的标准库"encoding/csv"将数据写入CSV文件。然而,文件中没有任何内容被写入,也没有返回任何错误。以下是写入代码。映射中的值是字符串数组。提前感谢任何帮助。
func writeErrors() {
file, error := os.OpenFile("output.csv", os.O_APPEND|os.O_CREATE, 0666 )
if error != nil {panic(error)}
defer file.Close()
// 新建Csv写入器
writer := csv.NewWriter(file)
// 表头
var new_headers = []string { "group_id", "account_id", "location_id", "payment_rating", "records_with_error" }
returnError := writer.Write(new_headers)
if returnError != nil {
fmt.Println(returnError)
}
for key, value := range errors {
returnError := writer.Write(value)
if returnError != nil {
fmt.Println(returnError)
}
fmt.Println("Writing: ", key, value)
}
}
英文:
I am trying to write to a csv file in GO using the standard library "encoding/csv" that comes with GO. However, nothing is being written to the file and there are no errors returning either. Below is the writing code. The values in the map are string arrays. Thanks for any help in advance.
func writeErrors() {
file, error := os.OpenFile("output.csv", os.O_APPEND|os.O_CREATE, 0666 )
if error != nil {panic(error)}
defer file.Close()
// New Csv writer
writer := csv.NewWriter(file)
// Headers
var new_headers = []string { "group_id", "account_id", "location_id", "payment_rating", "records_with_error" }
returnError := writer.Write(new_headers)
if returnError != nil {
fmt.Println(returnError)
}
for key, value := range errors {
returnError := writer.Write(value)
if returnError != nil {
fmt.Println(returnError)
}
fmt.Println("Writing: ", key, value)
}
}
答案1
得分: 8
你需要在writer.Write()
之后调用writer.Flush()
。
//来自包文档
func (w *Writer) Flush()
Flush将任何缓冲的数据写入底层的io.Writer。
英文:
You need to call writer.Flush()
after writer.Write()
//from package documentation
func (w *Writer) Flush()
Flush writes any buffered data to the underlying io.Writer.
答案2
得分: 7
有一个额外的标志,因为您直接调用os.OpenFile而不是通过os.Create来传递O_RDWR。您需要同时传递O_RDWR或O_WRONLY以及您的O_APPEND | O_CREATE标志。
O_APPEND仅用于表示在写入时写入应追加到文件末尾,它不指定打开模式本身。
附加说明:
您将“error”用作变量名,实际上这是Go中的一种类型,命名错误返回变量的惯用方法是“err”。
英文:
There is an additional flag, as you are calling os.OpenFile directly instead of via os.Create which passes O_RDWR for you. you need to either pass O_RDWR or O_WRONLY along with your O_APPEND | O_CREATE flags.
O_APPEND is only used to say that writes should be appended to the end of the file when writing, it doesn't specify the open mode itself.
Additional Note:
you're using "error" as a variable name, this is actually a type in Go, the idiom generally used for naming the error return variable is "err"
答案3
得分: 3
os.Create
打开一个可写的文件,可以从 源代码 和 文档 中了解到。
英文:
os.Create
opens a writeable file as can be learned from the source and the documentation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论