Home >Backend Development >Golang >How to Check for File Existence in Go?

How to Check for File Existence in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 13:22:30412browse

How to Check for File Existence in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn