To check if a file exists in Golang, you can use the “Stat()” and “isNotExists()” functions from the os package. The os.Stat() function returns a FileInfo structure containing information about the file. If the file exists, os.Stat() function returns nil and no error; if the file does not exist, it returns an error.
Syntax
fileInfo, error := os.Stat(fileName)
Parameters
fileName: The name of the file whose stats are to be retrieved.
Example: Checking If a File Exists in Golang
package main
import (
"fmt"
"os"
)
func fileExists(filename string) bool {
_, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func main() {
if fileExists("data.txt") {
fmt.Println("File exists")
} else {
fmt.Println("File does not exist")
}
}
Output
File exists
In this example, the os.Stat() function is called with the filename as its argument. The returned FileInfo structure is not used, and instead, the function checks the error returned by os.Stat(). If the error is nil, the file exists, and the function returns true.
If the error is not nil, the function checks if the error is an os.IsNotExist() function error returns false, suggesting that the file does not exist.
If the error is not an os.IsNotExist() function error, the function assumes that the file exists and returns true.
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.