我在用完全相同的代码在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.")
}
答案 0 :(得分:1)
Golang规范描述了OpenFile:
OpenFile是广义的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.")
}
标记在os/file.go的源代码中详细说明:
// 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.
)