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 }
Code language: Go (go)

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 }
Code language: Go (go)

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() }
Code language: Go (go)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments