How to check if a file exists in Go

0 min read 111 words

If you need to check if a file exists using Go, then you can use one of the following methods, depending on the version of Go you may be using.

If you are using Go >=1.13, then

file, err := os.OpenFile("/path/to/file.txt")
if errors.Is(err, os.ErrNotExist) {
    // The file does not exists
}

However, it is also possible to trap an error from an OpenFile attempt:

file, err := os.OpenFile("/path/to/file.txt")
if os.IsNotExist(err) {
    // The file does not exists
}

You can also confirm if the path is also not a directory as follows:

func fileExists(filename string) bool {
    info, err := os.Stat(filename)
    if os.IsNotExist(err) {
        return false
    }
    return !info.IsDir()
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts