Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

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

Posted on January 15, 2023October 4, 2023 by admin

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

Table of Contents

  • File Exists
  • Folder Exists

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)
}
  • directory
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2024 Welcome To Golang By Example | Design: Web XP