小编典典

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

go

Go的标准库没有专门用于检查文件是否存在的函数(如Python的os.path.exists)。什么是
惯用的 方式做到这一点?


阅读 394

收藏
2020-07-02

共1个答案

小编典典

要检查文件是否不存在,等同于Python的文件if not os.path.exists(filename)

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

要检查文件是否存在,等效于Python的文件if os.path.exists(filename)

编辑:根据最近的评论

if _, err := os.Stat("/path/to/whatever"); err == nil {
  // path/to/whatever exists

} else if os.IsNotExist(err) {
  // 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


}
2020-07-02