Reputation: 61
I am trying to create a file with directories and sub-directories. But Go always returns an error saying path not found. I want to create file with directories. I want a, b, c directories to be created(a/b/c) and c directory should have a file d.txt I have used os.Create and os.OpenFile
_, cerr := os.OpenFile("a/b/c/d.txt")
if cerr != nil {
log.Fatal("error creating a/b/c", cerr)
}
_, cerr := os.Create("a/b/c/d.txt")
if cerr != nil {
log.Fatal("error creating a/b/c", cerr)
}
path error
Upvotes: 0
Views: 1064
Reputation: 51652
You cannot create all missing directories and then the file with one function call. You can create all missing directories, and then the file, as follows:
_,err:=os.MkdirAll("a/b/c",perm)
f, err:=os.Create("a/b/c/d.txt")
You can also achieve this with:
name:="a/b/c/d.txt"
os.MkdirAll(filepath.Dir(name),perm)
f, err:=os.Create(name)
Upvotes: 9