gpt4 book ai didi

go - os.IsNotExist 但得到 "not a directory"

转载 作者:IT王子 更新时间:2023-10-29 02:05:39 26 4
gpt4 key购买 nike

我不明白,为什么我不能创建一个文件夹并写入一个文件,然后再次读入它 - 在相同的函数中使用相同的路径,只是为了测试?
当我在文件上运行“go test myio_test.go”时。我明白了

myio_test.go

...
func TestMyIo(t *testing.T) {

myio.CreateTempJsonFile()
}
....

myio.go

package myio

import (
"fmt"
"io/ioutil"
"path"
//"syscall"
// "os"
"bitbucket.org/kardianos/osext"
"os"
)

func CreateTempJsonFile() {

exePath, _ := osext.Executable()
filePath := path.Dir(exePath + "/json/")
fmt.Println("create: ", filePath)

_, errx := os.Stat(filePath)
if os.IsNotExist(errx) {
errm := os.Mkdir(filePath, 0644)
if errm != nil {
fmt.Println("error creating dir...")
panic(errm)
}
}

writeError := ioutil.WriteFile(filePath+"/user.txt", []byte(`{"user": "Mac"}`), 0644) // os.ModeTemporary)// 0644)
if writeError == nil {
fmt.Println("Ok write")
} else {
fmt.Println("Error write")
}

_, err := ioutil.ReadFile(filePath + "/user.txt")
if err == nil {
fmt.Println("Reading file")
} else {
fmt.Println("Error reading file")
}
}

就像 os.Stat(filePath) 认为文件夹已经存在一样。如果我然后删除对 os.Stat() 的检查,然后去创建文件夹,我会感到 panic “不是目录“?

fmt.Println("create: ", filePath) 打印:

/private/var/folders/yj/jcyhsxxj6ml3tdfkp9gd2wpr0000gq/T/go-build627785093/command-line-arguments/_test/myio.test/json

这很奇怪,因为每个测试都会创建一个新的“/go-buildxxx/”文件夹,因此该文件夹实际上不应该在那里?

有什么想法吗?

最佳答案

首先,您需要将可执行文件从它的基本路径中分离出来,因为它是从 osext

返回的
exePath, _ := osext.Executable()
base, _ := filepath.Split(exePath)

(或使用 osext.ExecutableFolder())

然后您需要创建具有0755 权限的目录。目录需要设置可执行位才能遍历它们。

关于go - os.IsNotExist 但得到 "not a directory",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27447305/

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