Home >Backend Development >Golang >How to Check if a File or Directory Exists in Go?
How to verify the existence of a file or directory in Go
In many programming scenarios, it becomes necessary to verify if a particular file or directory exists before proceeding with further operations. Go provides a simple and efficient way to perform this check.
To determine the existence of a file or directory, the os.Stat function can be leveraged. This function takes a path as its parameter and returns a FileInfo object which contains information about the file or directory.
To check for existence, the following code can be utilized:
import ( "os" ) func exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } else if os.IsNotExist(err) { return false, nil } return false, err }
This function returns a boolean indicating the existence of the file or directory and an error if encountered. The usage of os.IsNotExist allows for distinguishing between non-existing files or directories and other potential errors that may arise during the stat operation.
The above is the detailed content of How to Check if a File or Directory Exists in Go?. For more information, please follow other related articles on the PHP Chinese website!