Golang : Check if a file exist or not
In this tutorial, we will see how to check if a file exist or not before performing further operation.
checkfileexist.go
package main
import (
"fmt"
"os"
)
func main() {
file := "file.txt"
if _, err := os.Stat(file); err == nil {
fmt.Println(file, "exist!")
}
}
if the file.txt
is there, you should see the output
file.txt exist!
See also : Golang : Get file permission
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.8k Golang : convert int to string
+7.2k Golang : Gorrila mux.Vars() function example
+6.3k Golang & Javascript : How to save cropped image to file on server
+11.7k Golang : Fuzzy string search or approximate string matching example
+35.3k Golang : Upload and download file to/from AWS S3
+10.7k Golang : Create matrix with Gonum Matrix package example
+6.3k Golang : Get missing location after unmarshal binary and gob decode time.
+12.3k Golang : Pagination with go-paginator configuration example
+19.5k Golang : How to count the number of repeated characters in a string?
+10.8k Golang : Resolve domain name to IP4 and IP6 addresses.
+19.9k Golang : Append content to a file
+6.3k Linux/Unix : Commands that you need to be careful about