How to check if a file exists in Go?
Hello everyone! I'm a beginner Go developer writing a small tool for log processing. I need to check if a file exists on disk before opening it. In Python I'm used to os.path.exists(), but in Go I can't find an equivalent.
I tried using os.Stat(), but I'm not sure if that's correct. Here's my current code:
package main\n\nimport (\n "fmt"\n "os"\n)\n\nfunc main() {\n path := "/tmp/myfile.log"\n // How to check if file exists?\n _, err := os.Stat(path)\n if err == nil {\n fmt.Println("File exists!")\n } else {\n fmt.Println("File does not exist!")\n }\n}\n\n\nThe problem is that os.Stat() returns an error not only when the file doesn't exist, but also in other cases
No answers yet.
Log in to leave an answer