golang

How to check if file exists in Golang


In this article, you will learn about how to check if a file exists or not in Golang.

In Golang, you can check for the existence of a file by using Stat() function. It is provided by os package in Golang. Basically, the Stat() function returns a FileInfo with the named file and it will return a *PathError if there’s any error occurred.Let’s see our file structure first.

Here, in our file structure, we have two files one is main.go and another is test.go. Now we will check through the Stat() function if our test.go file is exists or not. Follow the code example below:

check if file exists in Golang

Here, we import our required packages first, and then we set the file name that exists in our directory. So the desired output will be “File exists”. Let’s see the output:

You can see the output in the terminal that is showing the existence of a file which is true.Now let’s try something different. let’s set a anonymous file name that does not exist and see what shows in the output.

check if file exists in Golang

You can see that we set a file name that does not exist in our directory. Now lets checkout the output from the terminal.

You can see the output which is indicating that the file or path doesn’t exists which is absolutely true as in our directory we don’t have any file named not-test.go.

This is how you can check if file exists or not by using Stat() function from os package in GoLang.


Share on social media

//