How to check if a file exists in Golang?


In order to check if a particular file exists inside a given directory in Golang, we can use the Stat() and the isNotExists() function that the os package of Go's standard library provides us with.

The Stat() function is used to return the file info structure describing the file. Let's first use the Stat() function only and see whether it will be enough to detect the presence of a file in Go.

Example 1

Consider the code shown below.

package main
import(
   "fmt"
   "os"
)
func main() {
   if _, err := os.Stat("sample.txt"); err == nil {
      fmt.Printf("File exists\n");
   } else {
      fmt.Printf("File does not exist\n");
   }
}

In the above code, we are trying to find the existence of a file named sample.txt with the help of the os.Stat() function, and then if we don't encounter an error we will get the first Printf() statement printed to the terminal.

Output

If we run the above code by using the command go run main.go, then we will get the following output in the terminal.

File exists

The above approach works well, but there's a catch. It might be so that the berr that is returned from the Stat() function can be due to permission error or failing disk, and hence it is always recommended to make use of the isNotExists(err) function as well along with the os.Stat() functions.

Example 2

Consider the code shown below.

package main
import(
   "fmt"
   "os"
)
func main() {
   if fileExists("sample.txt") {
      fmt.Println("sample file exists")
   } else {
      fmt.Println("sample file does not exist")
   }
}
func fileExists(filename string) bool {
   info, err := os.Stat(filename)
   if os.IsNotExist(err) {
      return false
   }
   return !info.IsDir()
}

Output

If we run the above code by making use of the go run main.go, then we will get the following output in the terminal.

File exists

Updated on: 01-Nov-2023

33K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements