How to check if a file exists in Go?

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

    What other answers missed, is that the path given to the function could actually be a directory. Following function makes sure, that the path is really a file.

    func fileExists(filename string) bool {
        info, err := os.Stat(filename)
        if os.IsNotExist(err) {
            return false
        }
        return !info.IsDir()
    }
    
    

    Another thing to point out: This code could still lead to a race condition, where another thread or process deletes or creates the specified file, while the fileExists function is running.

    If you're worried about this, use a lock in your threads, serialize the access to this function or use an inter-process semaphore if multiple applications are involved. If other applications are involved, outside of your control, you're out of luck, I guess.

提交回复
热议问题