gpt4 book ai didi

go - 在 Go 的父目录中递归查找具有名称的文件

转载 作者:IT王子 更新时间:2023-10-29 02:09:38 25 4
gpt4 key购买 nike

我有一个目录:

basepath + /my/sub/directory

在该子目录中,我有一个名为 file.json

的文件的多个实例

例子:

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

我想要做的是使用完整的目录路径并沿着文件树向上返回,直到我点击 basepath 并找到 file.json 的所有文件路径

我查看了 filepath.Walk 但它似乎是向下穿过目录树,而不是向上

最佳答案

这是一种您可以向后走并沿途读取每个 file.json 的方法。

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" }

希望您觉得这种方法有用。

关于go - 在 Go 的父目录中递归查找具有名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com