Golang: Check if file exists in go lang

It is easy to check if the file with the given path exists or not in Go lang. You can use 'Stat' method from 'os'.  Stat returns a FileInfo describing the named file. So if there is no error then you can safely assume the file exists.    

import (
	"fmt"
	"os"
)

func main() {
	if _, err := os.Stat("file.path"); err == nil {
		fmt.Println("File with given path exists.")
	} else if os.IsExist(err) {
		fmt.Printf("Path info error here. Error: %s", err.Error())
	} else {
		fmt.Println("File does not exist.")
	}
}

No comments:

Post a Comment

Caching is a technique used to store frequently accessed data in a temporary storage layer to improve system performance and reduce latency....