Cookies management by TermsFeed Cookie Consent

📂 Check if a file exists in Go

introduction file errors

Access to files in Go is provided by the os package. When the file does not exist, functions of this package return os.ErrNotExist error. As a result, to verify that the file exists, you need to check whether you received this error or not, for example, after opening the file when you want to do something with it like reading the first 100 bytes:

package main

import (
    "errors"
    "fmt"
    "log"
    "os"
)

func read100Bytes(path string) ([]byte, error) {
    file, err := os.Open(path)
    if errors.Is(err, os.ErrNotExist) {
        return nil, errors.New("file not exists error")
    }
    data := make([]byte, 100)
    _, err = file.Read(data)
    return data, err
}

func main() {
    path := "/foo/bar/file.go"
    data, err := read100Bytes(path)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(data))
}

Output:

2021/08/05 18:30:46 file not exists error
exit status 1

It’s also possible to check if a file exists without doing anything with it, but keep in mind that if you later want to do something with it, such as opening it, you should also check its existence as it may have been modified or deleted in the meantime:

package main

import (
    "errors"
    "fmt"
    "os"
)

func exists(path string) bool {
    _, err := os.Stat(path)
    return !errors.Is(err, os.ErrNotExist)
}

func main() {
    path := "/foo/bar/file.go"
    fileExists := exists(path)
    fmt.Printf("%s exists: %t\n", path, fileExists)
}

Output:

/foo/bar/file.go exists: false

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🕵️ Solve 'cannot take address of XXX' error in Go

Learn how to take the address of a literal, map value, or function return value
introduction pointer errors

📁 Create a directory in Go

Learn how to create a single or a hierarchy of directories
introduction file

📎 Convert JSON to CSV in Go

Learn how to transform JSON file to CSV
introduction file json csv