How to check if a file exists in Golang

Last updated on Jun 26, 2021 by Suraj Sharma

In this tutorial, you will learn how you can check if a file with a given file path exists in Golang 1.16

To check if a file exists, we use the os.Stat function, which returns a FileInfo describing the named file. If there is an error, the FileInfo will be of type *PathError.


package main

import (

func main () {
    if _, err:= os.Stat("./examples/file.txt"); errors.Is(err, fs.ErrNotExist){
    } else {
        fmt.Print("file exists")

Related Solutions

Rate this post

Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.