check if directory exists in go
To check if a directory exists in Go, you can use the os.Stat()
function. Here are the steps to do it:
- Import the necessary packages:
import (
"os"
)
- Use the
os.Stat()
function to get the file or directory information:
fileInfo, err := os.Stat("path/to/directory")
Note: Replace "path/to/directory"
with the actual path of the directory you want to check.
- Check if the error returned by
os.Stat()
indicates that the directory does not exist:
if os.IsNotExist(err) {
// Directory does not exist
// Handle the scenario accordingly
}
- Optionally, you can also check if the
fileInfo
returned byos.Stat()
is a directory:
if fileInfo.IsDir() {
// It is a directory
// Handle the scenario accordingly
} else {
// It is not a directory
// Handle the scenario accordingly
}
That's it! By following these steps, you can check if a directory exists in Go.