douquan1015 2017-07-16 06:00
浏览 355
已采纳

如何检查文件名(带有任何扩展名)在Golang目录中是否存在?

I know I could check the file does exist or not in Golang by the answers of the following questions.

The code looks like this.

_, 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)
}

But here's my real question, how do I check the filename does exist (has been used) in the specified directory? For example if I have a file tree like this:

--- uploads
       |- foo.png
       |- bar.mp4

I wanted to check if there's any file is using the specified name..

used := filenameUsed("uploads/foo")
fmt.Println(used) // Output: true

used = filenameUsed("uploads/hello")
fmt.Println(used) // Output: false

How do I implement the filenameUsed function?

Google gave me a path/filepath package as the result but I have no clue about how to use it.

  • 写回答

1条回答 默认 最新

  • dpyoh6553 2017-07-16 06:35
    关注

    You may use the filepath.Glob() function where you can specify a pattern to list files.

    The pattern to be used is basically the name you wish to check if used, extended with the any extension pattern.

    Example:

    func filenameUsed(name string) (bool, error) {
        matches, err := filepath.Glob(name + ".*")
        if err != nil {
            return false, err
        }
        return len(matches) > 0, nil
    }
    

    Using / testing it:

    fmt.Print("Filename foo used: ")
    fmt.Println(filenameUsed("uploads/foo"))
    fmt.Print("Filename bar used: ")
    fmt.Println(filenameUsed("uploads/bar"))
    

    Example output:

    Filename foo used: true <nil>
    Filename bar used: false <nil>
    

    However, note that filenameUsed() returning false (and nil error) does not mean a file with that name won't exist if you attempt to create one after. Meaning checking it and attempting to create such a file does not guarantee atomicity. If your purpose is to create a file if the name is not used, then simply try to create the file in the proper mode (do not overwrite if exists), and handle the (creation) error returned by that call.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?