douhengdao4499 2014-12-12 15:54
浏览 438
已采纳

os.IsNotExist但得到“不是目录”

I can not understand, why I am not able to create a folder and write to a file, and then read it in again - with the same path in same func, just for testing?
When I run "go test myio_test.go" on the file. I get

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")
    }
}

It is like the os.Stat(filePath) thinks the folder is already there. If I then remove the check for os.Stat() and just go and create the folder I get a panic "not a directory "?

fmt.Println("create: ", filePath) prints:

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

It is all strange, as each test creates a new "/go-buildxxx/" folder and therefore the folder should never actually be there?

Any ideas?

  • 写回答

1条回答 默认 最新

  • douye5949 2014-12-12 17:17
    关注

    First, you need to split off the executable from it's base path as it's returned from osext

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

    (or use osext.ExecutableFolder())

    Then you need to create the directory with the permissions 0755. Directories need the executable bit set in order to traverse them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧