How to check whether a file or directory exists?
More of an FYI, since I looked around for a few minutes thinking my question be a quick search away.
How to check if path represents an existing directory in Go?
This was the most popular answer in my search results, but here and elsewhere the solutions only provide existence check. To check if path
represents an existing directory, I found I could easily:
path := GetSomePath();
if stat, err := os.Stat(path); err == nil && stat.IsDir() {
// path is a directory
}
Part of my problem was that I expected path/filepath
package to contain the isDir() function.
// exists returns whether the given file or directory exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil { return true, nil }
if os.IsNotExist(err) { return false, nil }
return false, err
}
Edited to add error handling.
You can use this :
if _, err := os.Stat("./conf/app.ini"); err != nil {
if os.IsNotExist(err) {
// file does not exist
} else {
// other error
}
}
See : http://golang.org/pkg/os/#IsNotExist