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

标签 go

我不明白,为什么我不能创建一个文件夹并写入一个文件,然后再次读入它 - 在相同的函数中使用相同的路径,只是为了测试?
当我在文件上运行“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/

相关文章:

go - 如何将文件上传到 S3 Bucket/目录

go - 如何在Go中刷新tcp套接字?

json - 我如何解码这个 JSON

go - 有没有一种方法可以将字段添加到将提供给工作流中所有事件的工作流上下文中?

json - Go 中的嵌套数据结构 - Python 等价物

sql - 我可以通过 lib/pq Go SQL 驱动程序获得 EXPLAIN ANALYZE 输出吗?

file - 打开和写入文件时出错

go - 版本不匹配的 VSCode Golang dlv 调试错误

file - 将 *multipart.FileHeader 的内容读入 []byte

go - 未初始化的 channel 如何表现?