How to check whether a file or directory exists?

FileGo

File Problem Overview


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?

File Solutions


Solution 1 - File

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

Solution 2 - File

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

Solution 3 - File

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.

Solution 4 - File

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:

Solution 5 - File

I use the following function to check my directories for any errors. It's very similar to previous answers, but I think not nesting ifs makes the code more clear. It uses go-homedir to remove ~ from directory paths and pkg/errors to return nicer error messages, but it would be easy to take them out if you don't need their functionality.

// validateDirectory expands a directory and checks that it exists
// it returns the full path to the directory on success
// validateDirectory("~/foo") -> ("/home/bbkane/foo", nil)
func validateDirectory(dir string) (string, error) {
    dirPath, err := homedir.Expand(dir)
    if err != nil {
        return "", errors.WithStack(err)
    }
    info, err := os.Stat(dirPath)
    if os.IsNotExist(err) {
        return "", errors.Wrapf(err, "Directory does not exist: %v\n", dirPath)
    }
    if err != nil {
        return "", errors.Wrapf(err, "Directory error: %v\n", dirPath)

    }
    if !info.IsDir() {
        return "", errors.Errorf("Directory is a file, not a directory: %#v\n", dirPath)
    }
    return dirPath, nil
}

Also, to repeat @Dave C's comment, if the reason you're checking a directory's existence is to write a file into it, it's usually better to simply try to open it an deal with errors afterwards:

// O_EXCL - used with O_CREATE, file must not exist
file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
    return errors.WithStack(err)
}
defer file.Close()

Solution 6 - File

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhardPassView Question on Stackoverflow
Solution 1 - FileMostafaView Answer on Stackoverflow
Solution 2 - FileDenys SéguretView Answer on Stackoverflow
Solution 3 - FileEdward WagnerView Answer on Stackoverflow
Solution 4 - FileNikta JnView Answer on Stackoverflow
Solution 5 - FileBenView Answer on Stackoverflow
Solution 6 - FileKabeer ShaikhView Answer on Stackoverflow