How to check if a file exists in Go?

前端 未结 11 1745
陌清茗
陌清茗 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:38

    To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename):

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

    To check if a file exists, equivalent to Python's if os.path.exists(filename):

    Edited: per recent comments

    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
    
    
    }
    

提交回复
热议问题