douye2020
douye2020
2014-11-23 18:56

如何通过文件名(无扩展名)检查文件是否存在?

  • filesystems
  • search
已采纳

Question is quite self-explanatory.

Please, could anybody show me how can I check existence of the file by name (without extension) by short and efficient way. It would be great if code returns several occurrence if folder have several files with the same name.

Example:

folder/
  file.html
  file.md

UPDATE:

It is not obviously how to use one of filepath.Match() or filepath.Glob() functions by official documentation. So here is some examples:

matches, _          := filepath.Glob("./folder/file*") //returns paths to real files [folder/file.html, folder/file.md]
matchesToPattern, _ := filepath.Match("./folder/file*", "./folder/file.html") //returns true, but it is just compare strings and doesn't check real content
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongzi1209 dongzi1209 7年前

    You need to use the path/filepath package.

    The functions to check are: Glob(), Match() and Walk() — pick whatever suits your taste better.

    点赞 评论 复制链接分享
  • dqrm8199 dqrm8199 7年前

    Here is the updated code :

    package main
    
    import (
        "fmt"
        "os"
        "path/filepath"
        "regexp"
    )
    
    func main() {
        dirname := "." + string(filepath.Separator)
        d, err := os.Open(dirname)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        defer d.Close()
        fi, err := d.Readdir(-1)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        r, _ := regexp.Compile("f([a-z]+)le") // the string to match
        for _, fi := range fi {
            if fi.Mode().IsRegular() { // is file
                if r.Match([]byte(fi.Name())) { // if it match
                    fmt.Println(fi.Name(), fi.Size(), "bytes")
                }
            }
        }
    }
    

    With this one you can also search for date, size, include subfolders or file properties.

    点赞 评论 复制链接分享