Welcome To Golang By Example

Check if a file or directory exists in Go (Golang)

os.Stat and os.IsNotExist() can be used to check whether a particular file or directory exist or not.

File Exists   

package main

import (
    "log"
    "os"
)

func main() {
    fileinfo, err := os.Stat("temp.txt")
    if os.IsNotExist(err) {
        log.Fatal("File does not exist.")
    }
    log.Println(fileinfo)
}

Folder Exists

package main

import (
    "log"
    "os"
)

func main() {
    folderInfo, err := os.Stat("temp")
    if os.IsNotExist(err) {
        log.Fatal("Folder does not exist.")
    }
    log.Println(folderInfo)
}