在Go的父目录中递归查找名为的文件
我有一个目录:在Go的父目录中递归查找名为的文件,go,recursion,Go,Recursion,我有一个目录: basepath + /my/sub/directory 在该子目录中,我有一个名为file.json 例如: my/file.json my/sub/file.json my/sub/directory/file.json 我要做的是使用完整的目录路径,并沿着文件树走,直到我点击basepath并找到file.json的所有文件路径 我查看了filepath.Walk,但这似乎是通过目录树向下走,而不是向上走这里有一种方法,您可以向后走,一路上读取每个文件.json 项目目
basepath + /my/sub/directory
在该子目录中,我有一个名为file.json
例如:
my/file.json
my/sub/file.json
my/sub/directory/file.json
我要做的是使用完整的目录路径,并沿着文件树走,直到我点击basepath
并找到file.json
的所有文件路径
我查看了
filepath.Walk
,但这似乎是通过目录树向下走,而不是向上走这里有一种方法,您可以向后走,一路上读取每个文件.json
项目目录结构示例:
梅因,加油
输出: 希望你觉得这个方法有用
./
- main.go
./my
- file.json > {"location": "/my"}
./my/sub
- file.json > {"location": "/my/sub"}
./my/sub/dir
- file.json > {"location": "/my/sub/dir"}
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 += "/.."
}
}
{ "location": "/my/sub/dir" }
{ "location": "/my/sub" }
{ "location": "/my" }