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
+11.6k Golang : How to flush a channel before the end of program?
+15.6k Golang : Get all local users and print out their home directory, description and group id
+8.9k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+6.2k PHP : How to check if an array is empty ?
+5.4k Golang : Customize scanner.Scanner to treat dash as part of identifier
+32.3k Golang : Convert an image file to []byte
+10.1k Golang : Read file and convert content to string
+9.4k Golang : How to control fmt or log print format?
+12.6k Golang : Extract part of string with regular expression
+5.9k Golang : Find change in a combination of coins example
+7.6k Golang : Process json data with Jason package
+18.8k Golang : Find IP address from string