Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a file or directory exists? [duplicate]

Tags:

file

go

People also ask

How do you check if a file already exists?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .


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


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.


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:

  • mattes made this gist on Aug 6 '14
  • Sridhar Ratnakumar made this answer on Sep 21 '12