How to check if a file exists in Golang

In Golang, we can use the Stat() function in the os package to check if a file exists or not.

Syntax

fileInfo, error := os.Stat(fileName)

Parameters

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

Return value

The Stat() function returns an object that contains file information. If the file doesn’t exist, Stat() returns an error object.

This function can return an error due to other reasons as well. Therefore, to check if the error is the “file does not exist” error, we need to pass that error object to the os.IsNotExist() function. This function returns True if the error that was thrown is the “file does not exist” error, and vice versa.

Code example

The code snippet below demonstrates how to check if a file exists or not.

main.go
demo.txt
package main
import (
"os"
"fmt"
)
// function to check if file exists
func doesFileExist(fileName string) {
_ , error := os.Stat(fileName)
// check if error is "file not exists"
if os.IsNotExist(error) {
fmt.Printf("%v file does not exist\n", fileName)
} else {
fmt.Printf("%v file exist\n", fileName)
}
}
func main() {
// check if demo.txt exists
doesFileExist("demo.txt")
// check if demo.csv exists
doesFileExist("demo.csv")
}

Code explanation

In the code above, in line 9, we create the doesFileExist() function. This function uses the os.Stat() function to take a file name and read its stats.

If the file doesn’t exist, Stat() returns an error object. In line 13, we pass the error object to the os.IsNotExist() function to check the type of error.

Inside the main() function, in line 22, we call the doesFileExist() function and pass the name of an existing file, demo.txt. Since this file exists, we will see demo.txt file exist on the console.

In line 25, we call the doesFileExist() function again, but this time we pass the name of a non-existing file, demo.csv. Since this file doesn’t exist, we will see demo.csv file does not exist on the console.