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

How to Check for File Existence in Go?

Mary-Kate Olsen
Release: 2024-12-25 13:22:30
Original
355 people have browsed it

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
}
Copy after login

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.
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template