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
+16.3k Golang : Linked list example
+11.6k Golang : Transform comma separated string to slice example
+8.2k Golang : Timeout example
+30.3k Golang : Math pow(the power of x^y) example
+12.7k Golang : Fix image: unknown format error
+4.6k Golang : Shortening import identifier
+50.6k Golang : How to get time in milliseconds?
+13.4k Golang : How to filter a map's elements for faster lookup
+25.2k Golang : Encrypt and decrypt data with AES crypto
+12.1k Golang : Count number of runes in string
+18.3k Golang : Example for DSA(Digital Signature Algorithm) package functions
+7.9k Golang : Build and compile multiple source files