Home > Backend Development > Golang > How to check if a file exists in golang

How to check if a file exists in golang

Release: 2019-12-26 15:54:28
Original
2832 people have browsed it

How to check if a file exists in golang

Go language detects whether the file exists. First create a FileInfo. If no error is reported, then check whether it is a directory through IsDir():

finfo, err := os.Stat("filename.txt")
if err != nil {
    // no such file or dir
    return
}
if finfo.IsDir() {
    // it's a file
} else {
    // it's a directory
}
Copy after login

golang determines the file or file The method to determine whether the folder exists is to use the error value returned by the os.Stat() function:

If the error returned is nil, it means that the file or folder exists.

If the returned error type is judged to be true using os.IsNotExist(), it means that the file or folder does not exist.

If the error returned is of other types, it is not sure whether it exists.

For more golang knowledge, please pay attention to the golang tutorial column.

The above is the detailed content of How to check if a file exists in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template