We are going to start off by checking the existence of a file. So, to begin, let's create a file by clicking on New
| File
and naming it log.txt
.
To start checking whether the file exists, we are going to be using the os.Stat
package. It returns two values: the first one is the file info and the second one is the error. We don't need the file information but just the error itself because we are going to check the error to see whether the file exists. If the error is nil
(no error occurs), then the file exists. Check out the following code:
package main import ( "os" "fmt" ) func main(){ if _, err := os.Stat("log.txt"); err == nil{ fmt.Println("Log.txt file exists") } }
On running the preceding code, you'll obtain the following output:
To check whether the file exists in an opposite way, we just type os.IsNotExist()
and pass the err
that we captured and print it to the console. Check out the following code:
package main import ( "os" "fmt" ) func...