How to Check if a File Exists in Go

Created
Modified

Using os.Stat Function

Stat returns a FileInfo describing the named file. See the following example:

package main

import (
  "errors"
  "fmt"
  "os"
)

func main() {

  // since the addition of errors.Is in Go 1.13 (released in late 2019)
  if _, err := os.Stat("f.txt"); errors.Is(err, os.ErrNotExist) {
    fmt.Println(err)
  }
}
stat f.txt: no such file or directory

To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename).

Using os.Open Function

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError. For example,

package main

import (
  "errors"
  "fmt"
  "os"
)

func main() {

  if _, err := os.Open("f.txt"); errors.Is(err, os.ErrNotExist) {
    fmt.Println(err)
  }
}
open f.txt: no such file or directory

Related Tags

#check# #file#