简体   繁体   English

转到-遍历当前目录中的Directores /文件

[英]Go - Iterate through directores/files in current directory

I have the following structure: 我有以下结构:

project/
    docs/
        index.html
    root.html

I'm trying to iterate through this project structure so that I can read the contents of each file to process them. 我正在尝试遍历此项目结构,以便可以读取每个文件的内容以对其进行处理。 So I want to say "search through the directory project", then it will search through all the files, and only the first level of directories and their files, so if there was another directory with a file inside of docs/ , it would ignore it. 所以我想说“搜索目录项目”,然后它将搜索所有文件,并且仅搜索第一级目录及其文件,因此,如果在docs/内有另一个目录包含文件,它将忽略它。

Currently, I've tried to accomplish this with the "path/filepath" library: 目前,我尝试使用“ path / filepath”库来完成此操作:

func traverse(path string, file os.FileInfo, err error) error {
    if file, err := os.Open(file.Name()); err == nil {
        defer file.Close()
        if fileStat, err := file.Stat(); err == nil {
            switch mode := fileStat.Mode(); {
            case mode.IsDir():
                fmt.Println("it be a directory! lets traverse", file.Name())
                filepath.Walk(file.Name(), traverse)
            case mode.IsRegular():
                fmt.Println("the thingy ", file.Name(), " is a file")
            }
        } else {
            return errors.New("failed to check status")
        }
    }
    return errors.New("failed 2 open file/dir?")
}

Then I call it from here: 然后我从这里调用它:

if err := filepath.Walk("project/", traverse); err != nil {
    setupErr("%s", err)
}

Note that I run this executable relative to my test directory, so it's finding the directory okay. 请注意,我相对于我的测试目录运行此可执行文件,因此它可以找到该目录。 My problem is actually when I run it, I get the following: 我的问题实际上是在运行它时,我得到以下信息:

it be a directory! lets traverse project
it be a directory! lets traverse project
# ^ printed about 20 more times ^
failed 2 open file/dir?

I think my recursion is a little off, and it's not changing into the directory perhaps? 我认为我的递归有些差了,也许没有更改到目录中? Any ideas, if you need any more information just ask and I'll update. 任何想法,如果您需要更多信息,请询问,我会更新。

First, it looks like what you want do to contradicts with the code you have. 首先,看起来您想要做什么与您的代码相矛盾。 You wrote: 你写了:

So I want to say "search through the directory project", then it will search through all the files, and only the first level of directories and their files, so if there was another directory with a file inside of docs/, it would ignore it. 因此,我想说“搜索目录项目”,然后它将搜索所有文件,并且仅搜索第一级目录及其文件,因此,如果在docs /中存在另一个带有文件的目录,它将忽略它。

Does it mean that you want to iterate only two levels of directories (current and one below) and ignore the rest? 这是否意味着您只想迭代两级目录(当前目录和下一级),而忽略其余目录?

If so then you do not need a recursion, just a simple loop that executes search function over the files within the current directory and for every its subdirectory. 如果是这样,则您不需要递归,只需执行一个简单循环即可对当前目录中的文件及其每个子目录执行搜索功能。

The code that you have walks over the filesystem directory subtree. 您拥有的代码遍历文件系统目录子树。

Basically, filepath.Walk that you use should do it for you. 基本上,您使用的filepath.Walk应该为您完成。 So you either implement recursive walking or use Walk, but not both. 因此,您可以实施递归步行,也可以使用步行,但不能同时使用两者。

Second, the recursion is implemented incorrectly in your code. 其次,递归在您的代码中实现不正确。 It missing iterating over the directories. 它缺少对目录的迭代。

So the code that prints the file names in the current directory and its subdirectories (but not further) is: 因此,打印当前目录及其子目录(但不包括其他子目录)中文件名的代码为:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    items, _ := ioutil.ReadDir(".")
    for _, item := range items {
        if item.IsDir() {
            subitems, _ := ioutil.ReadDir(item.Name())
            for _, subitem := range subitems {
                if !subitem.IsDir() {
                    // handle file there
                    fmt.Println(item.Name() + "/" + subitem.Name())
                }
            }
        } else {
            // handle file there
            fmt.Println(item.Name())
        }
    }
}

Walk walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root. Walk遍历以root为根的文件树,为树中的每个文件或目录( 包括root)调用walkFn All errors that arise visiting files and directories are filtered by walkFn. 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. 步行不遵循符号链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM