Skip to content

Instantly share code, notes, and snippets.

@mattes
Last active June 6, 2026 21:11
Show Gist options
  • Select an option

  • Save mattes/d13e273314c3b3ade33f to your computer and use it in GitHub Desktop.

Select an option

Save mattes/d13e273314c3b3ade33f to your computer and use it in GitHub Desktop.
Check if file or directory exists in Golang
if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err) {
// path/to/whatever does not exist
}
if _, err := os.Stat("/path/to/whatever"); !os.IsNotExist(err) {
// path/to/whatever exists
}
@lukemilby

Copy link
Copy Markdown

I was here.

Thanks

@magicwarms

Copy link
Copy Markdown

Thanks!

@BloodmageThalnos

Copy link
Copy Markdown

shanks!

@stricklandye

Copy link
Copy Markdown

haha, although it is trivial still helps a lot ,thanks!

@mayooot

mayooot commented Feb 19, 2024

Copy link
Copy Markdown

Thanks

@lazypwny751

Copy link
Copy Markdown

thanks 👍

@Anhdao153

Copy link
Copy Markdown

thanks

@LassePladsen

LassePladsen commented Jun 6, 2026

Copy link
Copy Markdown

NB: as the docs say, you should rather now use errors.Is(err, fs.ErrNotExist) instead of os.IsNotExist(err):

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist).

https://pkg.go.dev/os#IsNotExist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment