How to check if a file exists in Go?

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

    Let's look at few aspects first, both the function provided by os package of golang are not utilities but error checkers, what do I mean by that is they are just a wrapper to handle errors on cross platform.

    So basically if os.Stat if this function doesn't give any error that means the file is existing if it does you need to check what kind of error it is, here comes the use of these two function os.IsNotExist and os.IsExist.

    This can be understood as the Stat of the file throwing error because it doesn't exists or is it throwing error because it exist and there is some problem with it.

    The parameter that these functions take is of type error, although you might be able to pass nil to it but it wouldn't make sense.

    This also points to the fact that IsExist is not same as !IsNotExist, they are way two different things.

    So now if you want to know if a given file exist in go, I would prefer the best way is:

    if _, err := os.Stat(path/to/file); !os.IsNotExist(err){
       //TODO
    } 
    

提交回复
热议问题