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
+30k Golang : Convert an image file to []byte
+9.9k Golang : Natural string sorting example
+22.3k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+4.1k Golang : micron to centimeter example
+17.3k Golang : Read binary file into memory
+12.1k Swift : Convert (cast) Int to String ?
+7.3k Your page has meta tags in the body instead of the head
+6.4k Golang : Not able to grep log.Println() output
+26.1k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+4.8k Fix fatal error: evacuation not done in time problem