当前位置: > > > > Golang csv在linux上写空
Golang csv在linux上写空
来源:stackoverflow
2024-04-23 12:15:43
0浏览
收藏
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Golang csv在linux上写空》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
我在linux上编写csv文件时遇到问题,使用完全相同的代码,它可以在windows上运行,但在linux(centos7)上没有任何内容写入文件:
package main
import (
"os"
"fmt"
"encoding/csv"
)
var data = [][]string{
{"1","2","3","4","5"},
{"a","b","c","d","f"},
}
func main() {
filename := "example.csv"
fp,e := os.OpenFile(filename, os.O_CREATE|os.O_APPEND, os.ModePerm)
if nil != e {
fmt.Printf("Open file '%s' failed: %s\n", filename, e)
os.Exit(1)
}
defer fp.Close()
w := csv.NewWriter(fp)
defer w.Flush()
for _,l := range data {
if e := w.Write(l); nil != e {
fmt.Printf("Write csv failed: %s\n",e)
os.Exit(1)
}
}
fmt.Println("Done.")
}
解决方案
golang 规范描述 :
openfile 是广义的 open 调用;大多数用户会使用 open 或 而是创建。它打开具有指定标志的命名文件(o_rdonly 等)和烫发(在 umask 之前)(如果适用)。如果成功的话方法 返回的文件可用于 i/o。如果有错误的话, 将是 *patherror 类型。
您缺少写入使用 openfile 函数创建的文件的标志,这就是打开文件进行写入或读取但没有任何内容写入 csv 的原因。
package main
import (
"encoding/csv"
"fmt"
"os"
)
var data = [][]string{
{"1", "2", "3", "4", "5"},
{"a", "b", "c", "d", "f"},
}
func main() {
filename := "example.csv"
fp, e := os.openfile(filename, os.o_create|os.o_append|os.o_wronly, os.modeperm)
if nil != e {
fmt.printf("open file '%s' failed: %s\n", filename, e)
os.exit(1)
}
defer fp.close()
w := csv.newwriter(fp)
defer w.flush()
for _, l := range data {
if e := w.write(l); nil != e {
fmt.printf("write csv failed: %s\n", e)
os.exit(1)
}
}
fmt.println("done.")
}
的源代码中详细说明了标志:
// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
const (
// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
// The remaining values may be or'ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
)
今天关于《Golang csv在linux上写空》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注米云公众号!
