简体   繁体   中英

How to check file existence by its base name (without extension)?

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

You need to use the path/filepath package .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM