How to check if a file exists in Golang

#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.


Example

package main

import (
    "errors"
    "fmt"
    "io/fs"
    "os"
)

func main () {
    if _, err:= os.Stat("./examples/file.txt"); errors.Is(err, fs.ErrNotExist){
        fmt.Print(err.Error())
    } 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.