gpt4 book ai didi

linux - Golang csv 在 linux 上写空

转载 作者:IT王子 更新时间:2023-10-29 02:09:32 25 4
gpt4 key购买 nike

我在 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 :

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.

您缺少写入使用 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.")
}

Playground Example

标志在源代码中详细说明 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.

)

关于linux - Golang csv 在 linux 上写空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51463210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com