【发布时间】:2017-12-20 21:17:52
【问题描述】:
我知道我可以通过以下问题的答案来检查该文件在 Golang 中是否存在。
- How to check whether a file or directory denoted by a path exists in Golang?
- How to check if a file exists in Go?
- Gist - Check if file or directory exists in Golang
代码如下所示。
_, err := os.Stat(path)
if err == nil {
log.Printf("File %s exists.", path)
} else if os.IsNotExist(err) {
log.Printf("File %s not exists.", path)
} else {
log.Printf("File %s stat error: %v", path, err)
}
但这是我真正的问题,我如何检查指定目录中的文件名是否存在(已被使用)?例如,如果我有这样的文件树:
--- uploads
|- foo.png
|- bar.mp4
我想检查是否有任何文件使用指定的名称..
used := filenameUsed("uploads/foo")
fmt.Println(used) // Output: true
used = filenameUsed("uploads/hello")
fmt.Println(used) // Output: false
如何实现filenameUsed 函数?
Google 结果给了我一个path/filepath 包,但我不知道如何使用它。
【问题讨论】:
标签: file go path directory file-exists