-
-
Save mattes/d13e273314c3b3ade33f to your computer and use it in GitHub Desktop.
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 | |
} |
Why not use os.IsExist
instead of !os.IsNotExist
?
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
}
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
like!