搜索
首页后端开发Golang从树中清除仅包含空文件夹的文件夹

从树中清除仅包含空文件夹的文件夹

php小编小新在这里为大家介绍一个有关文件夹操作的小技巧——如何从树中清除仅包含空文件夹的文件夹。在日常的文件管理中,我们可能会遇到一些只包含空文件夹的文件夹,这些文件夹占用了存储空间,但却没有实际的内容。通过以下简单的操作,我们可以轻松地清除这些空文件夹,释放宝贵的存储空间,提高文件管理的效率。

问题内容

我有一片

type node struct {
   id       string
   children []node
}

我有一个以此切片为模型的目录结构。该目录中可能存在多层文件夹结构,最终其中没有任何文件。请参阅:ű

folder1/folder2/folder3/folder4
folder1/file1.txt

我想清理那些只有空文件夹的文件夹。因此,在此示例中,只有folder1 中会保留一个文件,下面的所有内容都将被删除。 但是我似乎想不出这样做的好主意。我完全可以创建一棵新树而不改变原始树,但我不知道如何有效地遍历这棵树并查看最后一个孩子是否没有孩子,然后返回到根并删除该孩子结果只是一个空文件夹列表。 任何想法都会受到欢迎!

我的初始解决方案仅删除叶子而不删除父文件夹:

func removeChildlessFolders(original, tree []Node) []Node {
    for i, node := range original {
        if len(node.Children) == 0 {
            continue
        }

        dir := Node{}
        dir.Id = node.Id
        dir.Children = append(dir.Children, node.Children...)
        tree = append(tree, dir)
        removeChildlessFolders(original[i].Children, node.Children)
    }

    return tree
}

解决方法

首先是个好问题,但其他人很难重现您拥有的用例。从下次开始尝试添加可重现的代码,人们可以使用它并快速测试他们的方法并给出结果。就像您已经传递了根但您如何初始化它一样?如果有人需要帮助你,他们需要先建树。一般来说,这是不方便的。尽管如此,让我们来看看解决方案。

目录结构

输入dir

test-folder
├── folder1
│   └── folder2
│       └── folder3
├── folder4
│   ├── folder5
│   └── joker
└── folder6
    └── file.txt

预期结果

test-folder
└── folder6
    └── file.txt

节点定义

首先,我不知道你是如何创建目录树的。如果您对它进行了硬编码,那么这是一个不同的问题,但是 n-ary 树通常填充的方式,那么您需要使用自引用指针定义 node 。不是精确切片。所以我会按以下方式定义节点

type node struct {
    id       string
    children []*node
}

辅助方法

这是一个检查路径是否指向目录的辅助方法

func ifdir(path string) bool {
    file, err := os.open(path)
    if err != nil {
        panic(err)
    }
    defer file.close()
    info, err := file.stat()
    if err != nil {
        panic(err)
    }
    if info.isdir() {
        return true
    }
    return false
}

如何填充树

这是使用 queue 输入 n-ary 树 的简单迭代方法。 golang不提供队列实现,但golang通道实际上只是队列。我将其保留为 500 因为我们无法在 golang 中创建动态缓冲通道。恕我直言,这个数字应该适用于几乎所有场景。

func buildtreefromdir(basedir string) *node {
    _, err := ioutil.readdir(basedir)
    if err != nil {
        return nil
    }
    root := &node{
        id: basedir,
    }
    //////////
    queue := make(chan *node, 500) // consider that there can not be any dir with > 500 depth
    queue <- root
    for {
        if len(queue) == 0 {
            break
        }
        data, ok := <-queue
        if ok {
            // iterate all the contents in the dir
            curdir := (*data).id
            if ifdir(curdir) {
                contents, _ := ioutil.readdir(curdir)

                data.children = make([]*node, len(contents))
                for i, content := range contents {
                    node := new(node)
                    node.id = filepath.join(curdir, content.name())
                    data.children[i] = node
                    if content.isdir() {
                        queue <- node
                    }
                }
            }
        }
    }
    return root
}

另一种辅助方法

这只是打印目录树。仅用于调试目的。

func printdirtree(root *node) {
    fmt.println(root.id)
    for _, each := range root.children {
        printdirtree(each)
    }
    if len(root.children) == 0 {
        fmt.println("===")
    }

}

最后是你的解决方案。

非常简单。如果您有任何疑问,请告诉我。

func recursiveemptydelete(root *node) {
    // if the current root is not pointing to any dir
    if root == nil {
        return
    }
    for _, each := range root.children {
        recursiveemptydelete(each)
    }
    if !ifdir(root.id) {
        return
    } else if content, _ := ioutil.readdir(root.id); len(content) != 0 {
        return
    }
    os.remove(root.id)
}

这里是 main()

func main() {
    root := buildTreeFromDir("test-folder")
    printDirTree(root)
    recursiveEmptyDelete(root)
}

以上是从树中清除仅包含空文件夹的文件夹的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
测试代码依赖于INET功能的代码测试代码依赖于INET功能的代码May 03, 2025 am 12:20 AM

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

将GO的错误处理方法与其他语言进行比较将GO的错误处理方法与其他语言进行比较May 03, 2025 am 12:20 AM

go'serrorhandlingurturnserrorsasvalues,与Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

设计有效界面的最佳实践设计有效界面的最佳实践May 03, 2025 am 12:18 AM

AnefactiveInterfaceoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForeabStractionTosWapImplementations withCallingCallingCode.3)

集中式错误处理策略集中式错误处理策略May 03, 2025 am 12:17 AM

集中式错误处理在Go语言中可以提升代码的可读性和可维护性。其实现方式和优势包括:1.将错误处理逻辑从业务逻辑中分离,简化代码。2.通过集中处理错误,确保错误处理的一致性。3.使用defer和recover来捕获和处理panic,增强程序健壮性。

init in Init函数的替代方案,用于go中的包装初始化init in Init函数的替代方案,用于go中的包装初始化May 03, 2025 am 12:17 AM

Ingo,替代词Inivuntionsionializatializatializationfunctionsandsingletons.1)customInitializationfunctions hallowexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssementializatizatupsetups.2)单次固定元素限制ininconinconcurrent

与GO接口键入断言和类型开关与GO接口键入断言和类型开关May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和错误。使用errors.is和错误。May 02, 2025 am 12:11 AM

Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

在GO中进行性能调整:优化您的应用程序在GO中进行性能调整:优化您的应用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器