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

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...