snippetgoCritical
How to check if a file exists in Go?
Viewed 0 times
checkexistshowfile
Problem
Does the Go standard library have a function which checks if a file exists (like Python's
Is there an idiomatic way to check file existence / non-existence?
os.path.exists).Is there an idiomatic way to check file existence / non-existence?
Solution
To check if a file doesn't exist, equivalent to Python's
To check if a file exists, equivalent to Python's
if not os.path.exists(filename):if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) {
// path/to/whatever does not exist
}To check if a file exists, equivalent 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 {
// Schrodinger: file may or may not exist. See err for details.
// Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence
}Code Snippets
if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) {
// path/to/whatever does not exist
}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 {
// Schrodinger: file may or may not exist. See err for details.
// Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence
}Context
Stack Overflow Q#12518876, score: 1141
Revisions (0)
No revisions yet.