How to test a file or directory exists in Go?

Posted on

How to test a path (a file or directory exists) in golang?

In Bash, the [ -e ] tests can test whether a file or a directory exist. What are the corresponding Go ways for the test?

You can use the `os.Stat()` and `os.IsNotExist()` standard libraries functions together to test whether a file or a directory exists in Go.

if _, err := os.Stat("/tmp/aaaa"); err != nil {
    if os.IsNotExist(err) {
        // file does not exists
    } else {
        // file exists

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.