Go os.IsNotExist但正在获取;“不是目录”;
我不明白,为什么我不能创建一个文件夹并写入一个文件,然后再次读取它-在同一个func中使用相同的路径,只是为了测试Go os.IsNotExist但正在获取;“不是目录”;,go,Go,我不明白,为什么我不能创建一个文件夹并写入一个文件,然后再次读取它-在同一个func中使用相同的路径,只是为了测试 当我在文件上运行“go test myio_test.go”时。我明白了 myio_测试 ... func TestMyIo(t *testing.T) { myio.CreateTempJsonFile() } .... 迈奥,走 package myio import ( "fmt" "io/ioutil" "path" //"sy
当我在文件上运行“go test myio_test.go”时。我明白了 myio_测试
...
func TestMyIo(t *testing.T) {
myio.CreateTempJsonFile()
}
....
迈奥,走
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()的检查并创建文件夹,我会得到一个恐慌“不是目录”
“
fmt.Println(“创建:”,文件路径)打印:
这很奇怪,因为每个测试都会创建一个新的“/go buildxxx/”文件夹,因此该文件夹实际上不应该存在
有什么想法吗?首先,当可执行文件从
osext
exePath, _ := osext.Executable()
base, _ := filepath.Split(exePath)
(或使用osext.ExecutableFolder()
)
然后您需要创建具有权限的目录
0755
。目录需要设置可执行位才能遍历它们。您是否尝试过改用andioutil.TempFile
?我认为错误在于bitbucket.org/kardianos/osext,因为它返回可执行文件所在的路径。当您使用Go run时,会在临时文件夹中生成一个可执行文件。如果你使用“go build”,然后在正确的文件夹中运行你的可执行文件,它可能会工作bit@fabrizioM,对于目录(包括SUID、SGID和sticky位),每个位的含义略有不同:
exePath, _ := osext.Executable()
base, _ := filepath.Split(exePath)