douyi1966
douyi1966
2018-06-26 20:22

在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 duanshan1511 3年前

    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.

    点赞 评论 复制链接分享