How to Check If a File Exists in Go

To check if a file exists in Golang, you can use the “Stat()” and “isNotExists()” functions from the os package. The os.Stat() function returns a FileInfo structure containing information about the file. If the file exists, os.Stat() function returns nil and no error; if the file does not exist, it returns an error.

Syntax

fileInfo, error := os.Stat(fileName)

Parameters

fileName: The name of the file whose stats are to be retrieved.

Example: Checking If a File Exists in Golang

package main

import (
  "fmt"
  "os"
)

func fileExists(filename string) bool {
  _, err := os.Stat(filename)
  if err != nil {
    if os.IsNotExist(err) {
      return false
    }
  }
  return true
}

func main() {
  if fileExists("data.txt") {
    fmt.Println("File exists")
  } else {
    fmt.Println("File does not exist")
  }
}

Output

File exists

In this example, the os.Stat() function is called with the filename as its argument. The returned FileInfo structure is not used, and instead, the function checks the error returned by os.Stat(). If the error is nil, the file exists, and the function returns true.

If the error is not nil, the function checks if the error is an os.IsNotExist() function error returns false, suggesting that the file does not exist.

If the error is not an os.IsNotExist() function error, the function assumes that the file exists and returns true.

That’s it.

Leave a Comment