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
+15.3k Golang : Linked list example
+6.8k Golang : Progress bar with ∎ character
+11.1k Golang : Compress and decompress file with compress/flate example
+14.6k Golang : How to generate QR codes?
+12k Golang : How to filter a map's elements for faster lookup
+20.9k Golang : convert rune to integer value
+12.6k Golang : Get current time from the Internet time server(ntp) example
+7.8k Golang : Use regular expression to get all upper case or lower case characters example
+10.4k Golang : ROT47 (Caesar cipher by 47 characters) example
+8.7k Golang : Create matrix with Gonum Matrix package example
+8.7k Golang : Natural string sorting example
+6.1k Golang : Scan files for certain pattern and rename part of the files