乐闻世界logo
搜索文章和话题

How to check if a file exists in go

2个答案

1
2

In Go, there are several ways to check if a file exists, but the most common and straightforward method is to use the os.Stat function and the os.IsNotExist function. Below is an example demonstrating how to use these two functions to check if a file exists:

go
package main import ( "fmt" "os" ) // fileExists checks if a file exists and returns a boolean value along with any potential errors func fileExists(filename string) (bool, error) { // Uses os.Stat to retrieve file information info, err := os.Stat(filename) if os.IsNotExist(err) { // If the returned error is of type os.IsNotExist, it indicates that the file does not exist return false, nil } // If info is not nil and there is no error, the file exists return !info.IsDir(), err } func main() { // Checks if the file "example.txt" exists exists, err := fileExists("example.txt") if err != nil { // If there is an error, print the error and exit fmt.Printf("Failed to check if file exists: %v\n", err) return } // Prints the appropriate message based on the existence flag if exists { fmt.Println("File exists.") } else { fmt.Println("File does not exist.") } }

In the above code, the fileExists function attempts to retrieve information about the specified file. If os.Stat returns an error and os.IsNotExist confirms that the error is due to the file not existing, then fileExists returns false and a nil error. If there is no error and info.IsDir() is also false (indicating that the path is not a directory), then the function returns true.

It is important to note that a file may be inaccessible for other reasons (e.g., permission issues), in which case os.Stat returns a non-nil error. In such cases, you may need to handle the specific error types accordingly.

2024年6月29日 12:07 回复

To check if a file does not exist, it is equivalent to Python's if not os.path.exists(filename):

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

To check if a file exists, it is equivalent to Python's if os.path.exists(filename):

Edit: Based on recent comments

go
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 { // Schrödinger's cat: the file may or may not exist. See err for details. // Therefore, do not use !os.IsNotExist(err) to test for file existence }
2024年6月29日 12:07 回复

你的答案