How to check if a file or directory exists in Go
There are two main approaches you can adopt to solve this problem. If you want
to open the file (or directory), you can use the os.Open
method, pass in the
file or directory name, then check the error with os.IsNotExist
to see if it
reports that the file or directory does not exist.
_, err := os.Open("filename.png")
if err != nil {
if os.IsNotExist(err) {
// File or directory does not exist
} else {
// Some other error such as missing permissions
}
}
If you merely want to check the existence of a file or directory without opening
it, you can use os.Stat
instead of os.Open
.
_, err := os.Stat("filename.png")
if err != nil {
if os.IsNotExist(err) {
// File or directory does not exist
} else {
// Some other error. The file may or may not exist
}
}
Conclusion
As you can see, its easy to determine if a file is a directory exists in Go using the approaches discussed in this article. If you know of a better or safer way to achieve the intended result, please mention it in the comments.
Thanks for reading, and happy coding!