douyi1966 2018-06-26 20:22
浏览 155
已采纳

在Go的父目录中以递归方式查找具有名称的文件

I have a directory:

basepath + /my/sub/directory

In that subdirectory, I have multiple instances of a file with name file.json

Example:

my/file.json
my/sub/file.json
my/sub/directory/file.json

What I want to do is use the full directory path and walk BACK up the file tree until I hit the basepath and find all the filepaths for the file.json

I looked at filepath.Walk but that seems to go downwards through the directory tree, not upwards

  • 写回答

1条回答 默认 最新

  • duanshan1511 2018-06-26 21:18
    关注

    Here's one way you can walk backwards and read each file.json along the way.

    Example project directory structure:

    ./
      - main.go
      ./my
        - file.json > {"location": "/my"}
        ./my/sub
          - file.json > {"location": "/my/sub"}
          ./my/sub/dir
            - file.json > {"location": "/my/sub/dir"}
    

    main.go

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "path/filepath"
    )
    
    func main() {
        basePath := "./"
        targetPath := basePath + "my/sub/dir"
        fileName := "file.json"
    
        for {
            rel, _ := filepath.Rel(basePath, targetPath)
    
            // Exit the loop once we reach the basePath.
            if rel == "." {
                break
            }
    
            // Simple file reading logic.
            dat, err := ioutil.ReadFile(fmt.Sprintf("%v/%v", targetPath, fileName))
            if err != nil {
                panic(err)
            }
            fmt.Println(string(dat))
    
            // Going up!
            targetPath += "/.."
        }
    
    }
    

    Output:

    { "location": "/my/sub/dir" }
    { "location": "/my/sub" }
    { "location": "/my" }
    

    Hope you find this approach useful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?