There is a golang function that checks if a file exists. This function returns true if the file exists.

Why? If you try to open a file that doesn’t exist, at best it will return an empty string and at worst it will crash your program. That would lead to unexpected results and thus you want to check if the file exists.

File exists in golang

Example

The following golang code will check if the specified file exists or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"
import "os"

func main() {

if _, err := os.Stat("file-exists.go"); err == nil {
fmt.Printf("File exists\n");
} else {
fmt.Printf("File does not exist\n");
}
}

If no file root is specified, it will look for the file in the same directory as the code.
If the file exists, it will return true. If not, it will return false.

Error checking

Sometimes you want to check if a file exists before continuing the program. This leads to clean code: first check for errors, if no errors continue.

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"
import "os"

func main() {

if _, err := os.Stat("file-exists2.file"); os.IsNotExist(err) {
fmt.Printf("File does not exist\n");
}
// continue program

}

Exercises

  1. Check if a file exists on your local disk
  2. Can you check if a file exists on an external disk?