How to Check if a File Exists in Go

1. Introduction

Checking if a file exists before trying to read from it or write to it is an important operation in many applications. In Go, there are a few different ways to check for the existence of a file, most of which use the os package. This post will explain a straightforward method to perform this check.

Definition

The operation to check if a file exists involves using the os.Stat function and then examining the error that is returned. If the error is of type os.IsNotExist, it means the file does not exist.

2. Program Steps

1. Use os.Stat to retrieve the file status.

2. Handle the error returned by os.Stat to determine if the file exists or not.

3. Optionally, use os.IsNotExist to explicitly check the error type.

3. Code Program

package main

import (
	"fmt"
	"os"
)

func main() {
	// File paths for demonstration
	filePaths := []string{"existing_file.txt", "non_existing_file.txt"}

	for _, path := range filePaths {
		// Step 1: Use os.Stat to retrieve file status
		_, err := os.Stat(path)

		// Step 2: Handle the error
		if err == nil {
			fmt.Println(path, "exists.")
		} else if os.IsNotExist(err) {
			// Step 3: Use os.IsNotExist to explicitly check the error type
			fmt.Println(path, "does not exist.")
		} else {
			// Other error types might be related to permissions, etc.
			fmt.Println("Unable to check if file exists:", err)
		}
	}
}

Output:

existing_file.txt exists.
non_existing_file.txt does not exist.

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "os" - Importing the necessary packages for formatted output and operating system interactions.

3. filePaths is a slice of strings containing file paths to check for existence.

4. A for loop iterates through each path in filePaths.

5. os.Stat function attempts to get the file status, which is ignored here (_). The interest is in the error returned.

6. The if err == nil condition checks if the file exists without any errors.

7. The else if os.IsNotExist(err) condition checks if the error is because the file does not exist.

8. The else condition captures any other errors that might occur during the operation, such as permission issues.

9. fmt.Println prints the existence status of each file to the console.

10. The output shows which files exist and which do not, based on the dummy file paths provided.


Comments