Golang Code

Check If a File Exists Before Using It

· 121 words · 1 minute read #file #io #exists #check #os #stat #isnotexists

In this basic example, we check to see if a file exists before interacting with it (otherwise something’s not going to work as expected). We leverage the power of the os standard library and first use the Stat() function which although it’s usually used to get information about a file, we’re only looking at the errors.

We can’t just check for err == nil because any number of errors could be returned so we pass it to IsNotExists() to confirm that it’s an error because the file does not exist.

package main

import (
    "fmt"
    "os"
)

func main() {
    filename := "example.txt"
    if _, err := os.Stat(filename); os.IsNotExist(err) {
        fmt.Println("File does not exist")
    } else {
        fmt.Println("File exists")
    }
}
Image of Author Edd Turtle

Author: Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!