Avatar ·

How to check if a file exists in Go? (without unnecessary data races)

Hello everyone! I just started learning Go and encountered a seemingly simple task: I need to check if a file exists on disk before reading or writing it. In Python, I'm used to doing this: ```go import os if os.path.exists("myfile.txt"): print("File exists") ``` But in Go, I didn't find such a simple function. In the `os` package documentation, there is a `Stat()` function that returns an error if the file doesn't exist. I wrote this code: ```go package main import ( "fmt" "os" ) func main() { _, err := os.Stat("myfile.txt") if err != nil { if os.IsNotExist(err) { fmt.Println("File does not exist") } else { fmt.Println("Another error occurred:", err) } } else { fmt.Println("File ex