25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Checking if a File or Directory Exists in Go
Code Snippet

Checking if a File or Directory Exists in Go

go

Checking whether a file or directory exists is a common operation in Go programs. The os.Stat function returns file information, and by checking the error returned, you can determine if the path exists. The os.IsNotExist helper function makes this check clear and idiomatic.

When os.Stat is called on a non-existent path, it returns a non-nil error. Using os.IsNotExist(err) checks specifically for the “file not found” error condition, distinguishing it from other errors like permission denied. This is more reliable than checking error messages with string comparisons.

It’s important to note that os.Stat follows symbolic links, so if you need to check for the existence of a symlink itself, use os.Lstat instead. For simple existence checks in your application logic, this pattern is clean and efficient.

Further Reading: