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

How Can I Check for File Existence in Go?

Barbara Streisand
Release: 2024-12-26 21:28:10
Original
847 people have browsed it

How Can I Check for File Existence in Go?

Checking File Existence in Go

When working with files in Go, it's often necessary to determine if a file exists before proceeding with further operations. Unlike Python's os.path.exists, the Go standard library doesn't provide a direct function for this purpose.

Idiomatic Way to Check File Existence

To check if a file doesn't exist:

if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) {
  // path/to/whatever does not exist
}
Copy after login

To check if a file exists:

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

Explanation

The os.Stat function returns a FileInfo object representing the file's attributes or an error if the file doesn't exist. By using the errors.Is function to compare the error to os.ErrNotExist, you can distinguish between the file not existing and other errors.

Caution

Avoid using the negation of os.IsNotExist (e.g., !os.IsNotExist(err)) to test for file existence, as it can lead to unexpected behavior in some cases.

The above is the detailed content of How Can I 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