如何在Golang中检查目录中是否存在具有任何扩展名的文件`name`?

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

How to check file `name` (with any extension) does exist in the directory in Golang?

问题

我知道我可以通过以下问题的答案来检查在Golang中文件是否存在。

代码如下所示。

_, err := os.Stat(path)
if err == nil {
    log.Printf("文件 %s 存在。", path)
} else if os.IsNotExist(err) {
    log.Printf("文件 %s 不存在。", path)
} else {
    log.Printf("文件 %s 状态错误:%v", path, err)
}

但这是我的真正问题,我如何检查指定目录中的文件名是否存在(已被使用)?例如,如果我有以下文件树:

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

我想检查是否有任何文件正在使用指定的名称。

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

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

我该如何实现filenameUsed函数?

谷歌给出了一个path/filepath包作为结果,但我不知道如何使用它。

英文:

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

得分: 3

你可以使用filepath.Glob()函数来列出文件,其中可以指定一个模式来匹配文件。

要使用的模式基本上是你想要检查是否使用的名称,加上_任意扩展名_的模式。

示例:

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

使用/测试它:

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

示例输出:

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

但是,请注意,filenameUsed()返回false(和nil错误)并不意味着如果你尝试在之后创建一个文件,该名称的文件就不存在。这意味着检查它并尝试创建这样一个文件并不能保证原子性。如果你的目的是在名称未被使用时创建一个文件,那么只需尝试以正确的模式创建文件(如果存在则不覆盖),并处理该调用返回的(创建)错误即可。

英文:

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 + &quot;.*&quot;)
	if err != nil {
		return false, err
	}
	return len(matches) &gt; 0, nil
}

Using / testing it:

fmt.Print(&quot;Filename foo used: &quot;)
fmt.Println(filenameUsed(&quot;uploads/foo&quot;))
fmt.Print(&quot;Filename bar used: &quot;)
fmt.Println(filenameUsed(&quot;uploads/bar&quot;))

Example output:

Filename foo used: true &lt;nil&gt;
Filename bar used: false &lt;nil&gt;

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.

huangapple
  • 本文由 发表于 2017年7月16日 14:00:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/45125542.html
匿名

发表评论

匿名网友

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

确定