How to Check if a File Exists in Go

If you need to check if a file exists using Go, then you can use one of the following methods, depending on the version of Go you may be using.

If you are using Go >=1.13, then

file, err := os.OpenFile("/path/to/file.txt")
if errors.Is(err, os.ErrNotExist) {
    // The file does not exists
}

However, it is also possible to trap an error from an OpenFile attempt:

file, err := os.OpenFile("/path/to/file.txt")
if os.IsNotExist(err) {
    // The file does not exists
}

You can also confirm if the path is also not a directory as follows:

func fileExists(filename string) bool {
    info, err := os.Stat(filename)
    if os.IsNotExist(err) {
        return false
    }
    return !info.IsDir()
}