How to check if a file exists in Go?

前端 未结 11 1746
陌清茗
陌清茗 2020-11-30 16:23

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

11条回答
  •  -上瘾入骨i
    2020-11-30 16:39

    You should use the os.Stat() and os.IsNotExist() functions as in the following example:

    // Exists reports whether the named file or directory exists.
    func Exists(name string) bool {
        if _, err := os.Stat(name); err != nil {
            if os.IsNotExist(err) {
                return false
            }
        }
        return true
    }
    

    The example is extracted from here.

提交回复
热议问题