How to Check if File Exists in Go: Simple Guide
In Go, you can check if a file exists by using
os.Stat to get file info and then checking if the error returned is os.IsNotExist(err). If this returns true, the file does not exist; otherwise, it exists or another error occurred.Syntax
The basic syntax to check if a file exists uses the os.Stat function, which returns file information and an error. You then use os.IsNotExist(err) to check if the error means the file does not exist.
os.Stat(path): Gets file info or error for the given path.os.IsNotExist(err): Returns true if the error means the file does not exist.
go
info, err := os.Stat("filename.txt") if os.IsNotExist(err) { // file does not exist } else { // file exists or other error }
Example
This example shows how to check if a file named example.txt exists and prints a message accordingly.
go
package main import ( "fmt" "os" ) func main() { filename := "example.txt" _, err := os.Stat(filename) if os.IsNotExist(err) { fmt.Printf("File %s does not exist.\n", filename) } else if err != nil { fmt.Printf("Error checking file: %v\n", err) } else { fmt.Printf("File %s exists.\n", filename) } }
Output
File example.txt does not exist.
Common Pitfalls
One common mistake is to check if err == nil alone to decide if a file exists. This can miss other errors like permission issues. Always use os.IsNotExist(err) to specifically check for non-existence.
Also, do not assume that if os.Stat returns no error, the file is a regular file; it could be a directory or other file type.
go
package main import ( "fmt" "os" ) func main() { filename := "example.txt" _, err := os.Stat(filename) // Wrong: only checking err == nil if err == nil { fmt.Println("File exists") } else { fmt.Println("File does not exist or error") } // Right: use os.IsNotExist if os.IsNotExist(err) { fmt.Println("File does not exist") } else if err != nil { fmt.Printf("Other error: %v\n", err) } else { fmt.Println("File exists") } }
Output
File does not exist or error
File does not exist
Quick Reference
Remember these key points when checking file existence in Go:
- Use
os.Statto get file info. - Use
os.IsNotExist(err)to check if file is missing. - Handle other errors separately.
- Do not rely on
err == nilalone.
Key Takeaways
Use os.Stat to check file info and error.
Use os.IsNotExist(err) to detect if file does not exist.
Always handle other errors besides non-existence.
Do not rely only on err == nil to confirm file existence.
Check file type if needed, as os.Stat works for all file system objects.