Last active
May 3, 2024 22:20
-
-
Save mattes/d13e273314c3b3ade33f to your computer and use it in GitHub Desktop.
Check if file or directory exists in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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.
@digglife Welcome to this duck up Golang world.
👍
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");
}
@ravindrabhargava Please have a look at https://golang.org/pkg/path/filepath/#Glob
super!
Great! It was so helpful! 👍
Thanks 👍
Thanks
that helps~
Thanks
I was here.
Thanks
Thanks!
shanks!
haha, although it is trivial still helps a lot ,thanks!
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is an example to explain the difference, why
os.IsExist != !os.IsNotExist
: