Go: Check if a file or directory exists

Use the os.Stat and os.IsNotExist functions:

filepath := "/dev/null"
if _, err := os.Stat(filepath); !os.IsNotExist(err) {
	fmt.Println(filepath, "exists")
	// If there was an error, it wasn't a missing file
	// but something else, such as a permission error.
}

Output:

/dev/null exists
Warning: A file that is hidden from the current process will, of course, not be found.

Comments