如何通过文件的基本名称(不包括扩展名)检查文件是否存在?

huangapple go评论87阅读模式
英文:

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

问题

问题很明确。

请问有人可以向我展示如何通过文件名(不带扩展名)以简洁高效的方式检查文件的存在性吗?如果文件夹中有多个同名文件,代码能够返回多个匹配项就更好了。

示例:

folder/
  file.html
  file.md

更新:

根据官方文档,如何使用filepath.Match()filepath.Glob()函数并不明显。下面是一些示例:

matches, _ := filepath.Glob("./folder/file*") // 返回实际文件的路径 [folder/file.html, folder/file.md]
matchesToPattern, _ := filepath.Match("./folder/file*", "./folder/file.html") // 返回true,但只是比较字符串,不检查实际内容
英文:

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

答案1

得分: 3

你需要使用path/filepath

需要检查的函数有:Glob()Match()Walk(),选择适合你的喜好的函数即可。

英文:

You need to use the path/filepath package.

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

答案2

得分: 1

这是更新后的代码:

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") // 要匹配的字符串
	for _, fi := range fi {
		if fi.Mode().IsRegular() { // 是文件
			if r.Match([]byte(fi.Name())) { // 如果匹配成功
				fmt.Println(fi.Name(), fi.Size(), "bytes")
			}
		}
	}
}

使用这个代码,你还可以搜索日期、大小,包括子文件夹或文件属性。

英文:

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.

huangapple
  • 本文由 发表于 2014年11月24日 02:56:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/27092950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定