How to check if a file is a directory in Go

In this article, we’ll go over some ways to distinguish between files and directories in Go

Go provides an os.File type which represents an open file descriptor and is returned by methods such as os.Open:

path := "./path/to/fileOrDir"
file, err := os.Open(path)
if err != nil {
    // handle the error and return
}

defer file.Close()

The file returned here could either be a self-contained file or a directory containing other files. Here’s how to distinguish between the two:

// This returns an *os.FileInfo type
fileInfo, err := file.Stat()
if err != nil {
	// error handling
}

// IsDir is short for fileInfo.Mode().IsDir()
if fileInfo.IsDir() {
	// file is a directory
} else {
	// file is not a directory
}

If you want to check this information without opening the file, you can use os.Stat() and pass the path to the file.

path := "./path/to/fileOrDir"
fileInfo, err := os.Stat(path)
if err != nil {
	// error handling
}

if fileInfo.IsDir() {
	// is a directory
} else {
	// is not a directory
}

If you have to check for this often, consider wrapping up the code in function such as the one shown below:

// isDirectory determines if a file represented
// by `path` is a directory or not
func isDirectory(path string) (bool, error) {
	fileInfo, err := os.Stat(path)
	if err != nil {
		return false, err
	}

	return fileInfo.IsDir(), err
}

Conclusion

As you can see, determining if a file is a directory or not is pretty straightforward in Go. If you know of any other techniques different to what is posted above, please mention it in the comments.

Thanks for reading, and happy coding!