Golang spec described OpenFile:
OpenFile is the generalized open call; most users will use Open or
Create instead. It opens the named file with specified flag (O_RDONLY
etc.) and perm (before umask), if applicable. If successful, methods
on the returned File can be used for I/O. If there is an error, it
will be of type *PathError.
You are missing the flag to write to the file created using OpenFile
function that's the reason file is opened for writing or reading but nothing is written to the 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
", 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
", e)
os.Exit(1)
}
}
fmt.Println("Done.")
}
Playground Example
Flags are elaborated in source code for 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.
)