How to check if a file exists in Go?

前端 未结 11 1793
陌清茗
陌清茗 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条回答
  •  一个人的身影
    2020-11-30 16:52

    The example by user11617 is incorrect; it will report that the file exists even in cases where it does not, but there was an error of some other sort.

    The signature should be Exists(string) (bool, error). And then, as it happens, the call sites are no better.

    The code he wrote would better as:

    func Exists(name string) bool {
        _, err := os.Stat(name)
        return !os.IsNotExist(err)
    }
    

    But I suggest this instead:

    func Exists(name string) (bool, error) {
      _, err := os.Stat(name)
      if os.IsNotExist(err) {
        return false, nil
      }
      return err != nil, err
    }
    

提交回复
热议问题