How to check if a file exists in Go?

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

    basicly

    
    package main
    
    import (
        "fmt"
        "os"
    )
    
    func fileExists(path string) bool {
        _, err := os.Stat(path)
        return !os.IsNotExist(err)
    }
    
    func main() {
    
        var file string = "foo.txt"
        exist := fileExists(file)
        
        if exist {
            fmt.Println("file exist")
        } else {
    
            fmt.Println("file not exists")
        }
    
    }
    
    

    run example

    other way

    with os.Open

    package main
    
    import (
        "fmt"
        "os"
    )
    
    func fileExists(path string) bool {
        _, err := os.Open(path) // For read access.
        return err == nil
    
    }
    
    func main() {
    
        fmt.Println(fileExists("d4d.txt"))
    
    }
    
    
    

    run it

提交回复
热议问题