Checking File Existence in Go
In Go, there is no direct equivalent to Python's os.path.exists function for checking file existence. However, there are idiomatic ways to accomplish this task.
Checking File Non-Existence
To determine if a file does not exist, the following code can be used:
import ( "errors" "os" ) func fileDoesNotExist(path string) bool { _, err := os.Stat(path) return errors.Is(err, os.ErrNotExist) }
Checking File Existence
To ascertain if a file exists, the following code can be employed:
import ( "errors" "os" ) func fileExists(path string) bool { _, err := os.Stat(path) return err == nil }
Additional Considerations
It is important to note that using !os.IsNotExist(err) to check for file existence is not recommended. This method is not reliable because it can lead to false positives in scenarios where the file exists but is inaccessible for other reasons.
The above is the detailed content of How Can I Check for File Existence and Non-Existence in Go?. For more information, please follow other related articles on the PHP Chinese website!