List and access directory in go

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

List and access directory in go

问题

我需要一些帮助来编写一个能够在给定目录及其子目录中搜索特定单词的程序,使用的是golang语言。

以下是我目前的代码,用于列出目录并将它们保存为一个数组。现在我想检查每个目录,看看它们是否有子目录,如果有,我应该打开它们,直到达到树的最后一层。

package main

import (
    "fmt"
    "os"
)

func main() {

    d, err := os.Open("/Perkins")
    // fmt.Println(d.Readdirnames(-1))

    y, err := d.Readdirnames(-1)
    fmt.Println(y)
    for i := 0; i < len(y); i++ {
        if y[i] != " " {
            Folders := y[i]
            temp, err := os.Open("/" + Folders) //如何将数组元素作为路径输出?
            fmt.Println(temp)

            fmt.Println(err)
        }
    }
}

希望这能帮到你!

英文:

i need some help in golan to write a program that can search through a given directory and its subdirectories to look for a particular word word in each of them.

this what i have so far to list the directories and save them as an array. now i want to check each of them to see if it has children, if yes, i should open it until i reach the last level of the tree.

package main

import (
    &quot;fmt&quot;
    &quot;os&quot;
  
   
)

func main() {

    d, err := os.Open(&quot;/Perkins&quot;)
   // fmt.Println(d.Readdirnames(-1))
 
    y, err:=d.Readdirnames(-1) // 
   	fmt.Println(y)
   	for i:=0; i&lt;len(y); i++{
   		if y[i]!=&quot; &quot;{
   			Folders:=y[i]
   			temp,err:=os.Open(&quot;/&quot;Folders) //how do i out the array element as a path?
   			fmt.Println (temp)
   			
   			fmt.Println(err)
   			}
    }

答案1

得分: 2

注意:"/"Folders不起作用:"/" + Folders

在你的情况下,这样做可能更好:

temp, err := os.Open("/Perkins/" + Folders)

(尽管Folders不是一个好的变量名,subfolder可能更合适)


一个更高效的方法,正如chendesheng评论中提到的(参见答案),可以使用path/filepath/#Walk

package main

import (
  "fmt"
  "os"
  "path/filepath"
)

func main() {
  filepath.Walk("/Perkins", func(path string, info os.FileInfo, err error) error {
    fmt.Println(path)
    return nil
  })
}

这将列出所有文件,但你可以将其与一个过滤函数关联起来,参见这个示例

matched, err := filepath.Match("*.mp3", fi.Name())

然后你可以忽略你不想要的文件,只处理与你的模式匹配的文件。

英文:

Note: &quot;/&quot;Folders wouldn't work: &quot;/&quot; + Folders

In your case, this should work better:

temp,err:=os.Open(&quot;/Perkins/&quot; + Folders)

(even though 'Folders' is not a good name, 'subfolder' would be more appropriate)


A more efficient way, as commented by chendesheng (see answer), would be (as in this class) to use path/filepath/#Walk:

package main

import (
  &quot;fmt&quot;
  &quot;os&quot;
  &quot;path/filepath&quot;
)

func main() {
  filepath.Walk(&quot;/Perkins&quot;, func(path string, info os.FileInfo, err error) error {
    fmt.Println(path)
    return nil
  })
}

That will list all the file, but you can associate it with a function which will filter those: see this example:

matched, err := filepath.Match(&quot;*.mp3&quot;, fi.Name())

You can then ignore the files you don't want and proceed only for the ones matching your pattern.

答案2

得分: 2

我认为你可以使用filepath.Walk函数。

Walk函数遍历以root为根的文件树,在树中的每个文件或目录上调用walkFn函数,包括根目录。所有访问文件和目录时出现的错误都会由walkFn函数过滤。文件按字典顺序遍历,这使得输出是确定性的,但对于非常大的目录,Walk可能效率低下。Walk函数不会跟随符号链接。

英文:

I think you can use filepath.Walk

> Walk walks the file tree rooted at root, calling walkFn for each file
> or directory in the tree, including root. All errors that arise
> visiting files and directories are filtered by walkFn. The files are
> walked in lexical order, which makes the output deterministic but
> means that for very large directories Walk can be inefficient. Walk
> does not follow symbolic links.

答案3

得分: 0

也许你需要这个?
http://golang.org/pkg/io/ioutil/#ReadDir
然后检查类型来自http://golang.org/pkg/os/#FileInfo,如果是文件夹,则进行递归函数。

英文:

Maybe you need this?
http://golang.org/pkg/io/ioutil/#ReadDir
And then check is type from http://golang.org/pkg/os/#FileInfo and do recursive func if it folder

huangapple
  • 本文由 发表于 2014年7月16日 22:28:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/24783429.html
匿名

发表评论

匿名网友

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

确定