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

How Can I Check for File Existence and Non-Existence in Go?

Susan Sarandon
Release: 2024-12-22 12:01:44
Original
372 people have browsed it

How Can I Check for File Existence and Non-Existence in Go?

Checking File Existence in Go

In Go, there is no direct equivalent to Python's os.path.exists function for checking file existence. However, there are idiomatic ways to accomplish this task.

Checking File Non-Existence

To determine if a file does not exist, the following code can be used:

import (
    "errors"
    "os"
)

func fileDoesNotExist(path string) bool {
    _, err := os.Stat(path)
    return errors.Is(err, os.ErrNotExist)
}
Copy after login

Checking File Existence

To ascertain if a file exists, the following code can be employed:

import (
    "errors"
    "os"
)

func fileExists(path string) bool {
    _, err := os.Stat(path)
    return err == nil
}
Copy after login

Additional Considerations

It is important to note that using !os.IsNotExist(err) to check for file existence is not recommended. This method is not reliable because it can lead to false positives in scenarios where the file exists but is inaccessible for other reasons.

The above is the detailed content of How Can I Check for File Existence and Non-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