如何在遍历文件夹时过滤子文件夹?

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

How to filter sub-folder when Walk folder

问题

现在我正在使用Walk函数遍历我的文件夹,我想在扫描时过滤一些文件夹。

err := filepath.Walk("/home", func(path string, f os.FileInfo, err error) error {
    ...
})

文件夹结构如下:

home  
/ | \  
a  b  c  

我能否创建一个例外列表,让filepath.Walk不扫描文件夹a?也就是说,我不希望文件夹a中的任何文件被添加到我的扫描结果中。

英文:

Now I am using Walk to go through my folder, I want to filter some folder when scan.

err := filepath.Walk("/home", func(path string, f os.FileInfo, err error) error {
    ...
})

The folder structure is:

  home  
 / | \  
a  b  c  

Can I make some exception list that filepath.Walk not scan folder a? That is, I do not want any files in folder a add into my scan result.

答案1

得分: 6

根据WalkFunc的文档:

> 如果返回一个错误,处理将停止。唯一的例外是,如果路径是一个目录并且函数返回特殊值SkipDir,目录的内容将被跳过,处理将继续在下一个文件上正常进行。

因此,当path是你想要跳过的目录时,只需让你传递给filepath.Walk的函数返回filepath.SkipDir

英文:

From the documentation for WalkFuc:

> If an error is returned, processing stops. The sole exception is that if path is a directory and the function returns the special value SkipDir, the contents of the directory are skipped and processing continues as usual on the next file.

So simply make the function you pass to filepath.Walk return filepath.SkipDir when path is the directory you want skipped.

huangapple
  • 本文由 发表于 2014年4月30日 11:18:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/23379066.html
匿名

发表评论

匿名网友

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

确定