Skip to content

Instantly share code, notes, and snippets.

@mattes
Last active May 3, 2024 22:20
Show Gist options
  • Save mattes/d13e273314c3b3ade33f to your computer and use it in GitHub Desktop.
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
}
@SteelCrow
Copy link

Backslash \ is escape character, that's why I think you getting this strange behaviour.

@daqing613
Copy link

Thanks.

@ilyaiqoqo
Copy link

like!

@danawoodman
Copy link

Why not use os.IsExist instead of !os.IsNotExist?

@mattes
Copy link
Author

mattes commented Oct 21, 2019

Here is an example to explain the difference, why os.IsExist != !os.IsNotExist:

if _, err := os.Stat("/path/to/whatever"); os.IsExist(err) {
	// never triggers, because err is nil if file actually exists
}
if err := os.Mkdir("/path/to/whatever", 0755); os.IsExist(err) {
	// triggers if dir already exists
}

@digglife
Copy link

digglife commented Apr 13, 2020

Is this normal? Have anyone here ever typed this long to just test if a file/dir exists in any other modern language?

Thanks for the solution tho.

@rickyzhang82
Copy link

@digglife Welcome to this duck up Golang world.

@kfelter
Copy link

kfelter commented Aug 18, 2020

👍

@ravindrabhargava
Copy link

what about if need to check for "*.txt" in Linux dir if the file exists or not, I tried *.txt but it's not working at all

if _, err := os.Stat("*.txt"); err == nil {
fmt.Printf("File exists\n");
} else {
fmt.Printf("File does not exist\n");
}

@mattes
Copy link
Author

mattes commented Sep 21, 2020

@pavelerokhin
Copy link

super!

@KEINOS
Copy link

KEINOS commented Mar 21, 2021

Great! It was so helpful! 👍

@ondrejsika
Copy link

Thanks 👍

@gowizzard
Copy link

Thanks

@9cat
Copy link

9cat commented Apr 27, 2022

that helps~

@yangyongzhi7
Copy link

Thanks

@lukemilby
Copy link

I was here.

Thanks

@magicwarms
Copy link

Thanks!

@BloodmageThalnos
Copy link

shanks!

@stricklandye
Copy link

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

@mayooot
Copy link

mayooot commented Feb 19, 2024

Thanks

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