Access to files in Go is provided by the os
package. When the file does not exist, functions of this package return os.ErrNotExist
error. As a result, to verify that the file exists, you need to check whether you received this error or not, for example, after opening the file when you want to do something with it like reading the first 100 bytes:
package main
import (
"errors"
"fmt"
"log"
"os"
)
func read100Bytes(path string) ([]byte, error) {
file, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return nil, errors.New("file not exists error")
}
data := make([]byte, 100)
_, err = file.Read(data)
return data, err
}
func main() {
path := "/foo/bar/file.go"
data, err := read100Bytes(path)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
}
Output:
2021/08/05 18:30:46 file not exists error
exit status 1
It’s also possible to check if a file exists without doing anything with it, but keep in mind that if you later want to do something with it, such as opening it, you should also check its existence as it may have been modified or deleted in the meantime:
package main
import (
"errors"
"fmt"
"os"
)
func exists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
func main() {
path := "/foo/bar/file.go"
fileExists := exists(path)
fmt.Printf("%s exists: %t\n", path, fileExists)
}
Output:
/foo/bar/file.go exists: false