Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file exists in Go?

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?

like image 264
Sridhar Ratnakumar Avatar asked Sep 20 '12 18:09

Sridhar Ratnakumar


People also ask

How do you check if a file exist in Golang?

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.

How do you check if file is exists?

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 .

How do I delete a file in go?

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.


1 Answers

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   } 
like image 77
Sridhar Ratnakumar Avatar answered Oct 10 '22 07:10

Sridhar Ratnakumar