How can I get the top path of glob path?

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

How can I get the top path of glob path?

问题

为了实现你的目的,你可以使用filepath.Dir函数来获取文件路径的上级目录。在你的代码示例中,你可以将top设置为filepath.Dir(p),这样就可以得到glob路径的绝对路径。修改后的代码如下所示:

files, _ := filepath.Glob(p)
top := filepath.Dir(p)
for _, f := range files {
    abs, _ := filepath.Abs(path.Join(top, f))
    fmt.Println(abs)
}

这样,你就可以得到glob文件名的绝对路径了。

英文:

e.g.

a/b/c* -> a/b
a/b/c*/*/*b -> a/b

Why I need this is because I want to get the abs path of globed filename.
Code example:

files, _ := filepath.Glob(p)
top := __magic here__
for _, f := range files {
	abs, _ := filepath.Abs(path.Join(top, f))
	fmt.Println(abs)
}

Is there any exists method for this purpose? otherwise I have to implement by myself.

EDIT

The magic is make glob path abs first, then the glob return abs path.

答案1

得分: 0

filepath.Glob() 返回的文件名已经是绝对路径(但请参阅下文)。

看下面的示例:

fs, err := filepath.Glob("/dev/../dev/*")
if err != nil {
    panic(err)
}
for _, f := range fs {
    fmt.Println(f, filepath.IsAbs(f))
}

输出结果:

/dev/null true
/dev/random true
/dev/urandom true
/dev/zero true

在<kbd>Go Playground</kbd>上尝试一下。

编辑:

只有当通配符模式是绝对路径时,返回的文件名才是绝对路径。所以最简单的方法是将通配符模式设为绝对路径。

英文:

File names returned by filepath.Glob() are already absolute (but read below).

See this example:

fs, err := filepath.Glob(&quot;/dev/../dev/*&quot;)
if err != nil {
	panic(err)
}
for _, f := range fs {
	fmt.Println(f, filepath.IsAbs(f))
}

Output:

/dev/null true
/dev/random true
/dev/urandom true
/dev/zero true

Try it on the <kbd>Go Playground</kbd>.

Edit:

The returned file names are only absolute if the glob pattern is absolute. So the easiest way is to make the glob pattern absolute.

huangapple
  • 本文由 发表于 2015年6月26日 18:55:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/31071382.html
匿名

发表评论

匿名网友

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

确定