首页 >后端开发 >Golang >Go中如何检查文件是否存在?

Go中如何检查文件是否存在?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-12-25 13:22:30424浏览

How to Check for File Existence in Go?

如何在 Go 中确定文件存在

在 Go 中,标准库没有提供专门用于检查文件存在的显式函数。然而,确定文件存在/不存在的惯用方法是通过 os.Stat 函数。

检查文件是否不存在

检查文件是否存在不存在,类似于Python的os.path.exists(filename):

if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) {
    // /path/to/whatever does not exist
}

检查文件是否存在

检查文件是否存在,类似于 Python 的 if os.path.exists (文件名):

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 {
    // File existence uncertain. Refer to `err` for details.
    // **Do not** use `!os.IsNotExist(err)` to determine file existence.
}

以上是Go中如何检查文件是否存在?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn