Menu Close

Go – How to check if a file exists in Go

Here, We will see how to check if a file exists in Go. We can do it by using Stat() function in os package in go golang.

Function prototype:

func Stat(name string) (FileInfo, error)

Input Parameter:

name : file name

Return value:

Stat() function in os package returns
a FileInfo describing the named file.

If there is an error, it will be of type 

Example with code:

package main

import (



func main() {

  file_name := "/Usr/sample.go"

  if _, err := os.Stat(file_name); err == nil {

    fmt.Println("File exists")

  } else if os.IsNotExist(err) {

    fmt.Println("File or path doesn't exists")

  } else {





File exists

To learn more about golang, Please refer given below link:

Posted in golang, os, packages

Leave a Reply

Your email address will not be published. Required fields are marked *