Home > Article > Backend Development > Golang io method to read files and determine whether files exist
one. To determine whether a file exists, you need to use two functions in the "os" package: os.Stat() and os.IsNotExit()
func (f *File) Stat() (fi FileInfo, err error)
Stat returns a FileInfo type value describing file f. If an error occurs, the underlying error type is *PathError.
func IsNotExist(err error) bool
Returns a Boolean value indicating whether the error indicates that a file or directory does not exist. ErrNotExist and some system call errors will return true.
The method for Golang to determine whether a file or folder exists is to use the error value returned by the os.Stat() function to determine:
1. If the returned error is nil, it indicates that the file or folder exists. The folder exists
2. If the returned error type is judged to be true using os.IsNotExist(), it means that the file or folder does not exist
3. If the returned error is of other types, it does not Determine whether there is
func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }
The code can be simplified:
if _, err := os.Stat(path); os.IsNotExist(err){ return err }
2. To read the contents of the file, you need to use the "io/ioutil" package
fileContent, err := ioutil.ReadFile(load) if err != nil { log.Panic(err) }
For more golang knowledge, please pay attention to the golang tutorial column.
The above is the detailed content of Golang io method to read files and determine whether files exist. For more information, please follow other related articles on the PHP Chinese website!