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
+4.7k Golang : Stop goroutine without channel
+13.3k Golang : How to check if your program is running in a terminal
+11.9k Golang : http.Get example
+6.5k Golang : alternative to os.Exit() function
+23.1k Golang : Call function from another package
+18.3k Mac OSX : Homebrew and Golang
+7.4k Golang : Reverse text lines or flip line order example
+11.5k Golang : Listen and Serve on sub domain example
+9.7k Golang : Flip coin example
+20.4k Golang : Convert(cast) string to rune and back to string example
+11.5k Golang : Search and extract certain XML data example
+6.7k Golang : Handling Yes No Quit query input