How to Ascertain File Existence in Go
In Go, the standard library does not provide an explicit function solely dedicated to checking file existence. However, an idiomatic approach to determine file existence/non-existence is through the os.Stat function.
Checking for File Non-Existence
To check if a file does not exist, similar to Python's os.path.exists(filename):
if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) { // /path/to/whatever does not exist }
Checking for File Existence
To check if a file exists, akin to Python's if os.path.exists(filename):
if _, err := os.Stat("/path/to/whatever"); err == nil { // /path/to/whatever exists } else if errors.Is(err, os.ErrNotExist) { // /path/to/whatever does *not* exist } else { // File existence uncertain. Refer to `err` for details. // **Do not** use `!os.IsNotExist(err)` to determine file existence. }
The above is the detailed content of How to Check for File Existence in Go?. For more information, please follow other related articles on the PHP Chinese website!