Ben Chuanlong Du's Blog

It is never too late to learn.

Check Whether a Path Exists in Golang

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips & Traps

There is no built-in function to check for the existence of a path in Golang. However, you can achieve it using os.Stat + os.IsNotExist.

In [1]:
import "os"
In [2]:
_, err := os.Stat("/some/non-exist/path")
In [3]:
err
Out[3]:
stat /some/non-exist/path: no such file or directory
In [6]:
os.IsNotExist(err)
Out[6]:
true

The function ExistsPath below is an implementation based the idea abvoe.

In [7]:
func ExistsPath(path string) bool {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		return false
	}
	return true
}
In [8]:
ExistsPath("/some/non-exist/path")
Out[8]:
false
In [ ]:
 

Comments