Go's standard library does not have a function solely intended to check if a file exists or not (like Python's os.path.exists
). What is the idiomatic way to do it?
In order to check if a particular file exists inside a given directory in Golang, we can use the Stat() and the isNotExists() function that the os package of Go's standard library provides us with. The Stat() function is used to return the file info structure describing the file.
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
To remove a file in Golang, use the os. Remove() function. You need to provide a filepath to that file, and the function removes that file. Golang Remove() removes the named file or (empty) directory.
To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename)
:
if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) { // path/to/whatever does not exist }
To check if a file exists, equivalent to Python's if os.path.exists(filename)
:
Edited: per recent comments
if _, err := os.Stat("/path/to/whatever"); err == nil { // path/to/whatever exists } else if errors.Is(err, os.ErrNotExist) { // path/to/whatever does *not* exist } else { // Schrodinger: file may or may not exist. See err for details. // Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With