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 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)