如何检查文件或目录是否存在?

I want to check the existence of file ./conf/app.ini in my Go code, but I can't find a good way to do that.

I know there is a method of File in Java: public boolean exists(), which returns true if the file or directory exists.

But how can this be done in Go?

// 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 true, 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

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.

There is simple way to check whether your file exists or not:

if _, err := os.Stat("./conf/app.ini"); err != nil {
    if os.IsNotExist(err) {
        ..... //Shows error if file not exists
    } else {
       ..... // Shows success message like file is there
    }
}

Simple way to check whether file exists or not:

if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err) {
    // path/to/whatever does not exist
}

if _, err := os.Stat("/path/to/whatever"); err == nil {
    // path/to/whatever exists
}

Sources: