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.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀