简体   繁体   English

按特定顺序遍历子文件夹

[英]Iterate through subfolders in a specific order

At work we sometimes need to set up project folders with many subfolders, we try to keep them all consistent and so I'm trying to automate it.在工作中,我们有时需要设置包含许多子文件夹的项目文件夹,我们尝试使它们保持一致,因此我正在尝试将其自动化。 I want to be able to specify a folder structure and how many instances I want, and then see a preview of the finished file structure.我希望能够指定一个文件夹结构以及我想要多少个实例,然后查看完成的文件结构的预览。 Right now I can create a folder class and put other folder classes into it as subfolders:现在我可以创建一个文件夹 class 并将其他文件夹类作为子文件夹放入其中:

class Folder:
     def __init__(self, name, level, subfolders):
          self.name = name
          self.level = level # not sure I actually need this, was trying to keep track of how deep the folder is
          self.subfolders = subfolders # this is just other class instances

Now for example, lets say I had a folder called "New Project", it's subfolders / classes were "CAD", "Admin", and "Client Data", and then "CAD" had a subfolder / class called "Old".现在例如,假设我有一个名为“New Project”的文件夹,它的子文件夹/类是“CAD”、“Admin”和“Client Data”,然后“CAD”有一个名为“Old”的子文件夹/class。 I would want my text preview in the GUI to look like this:我希望我在 GUI 中的文本预览看起来像这样:

My Project
    CAD
        Old
    Admin
    Client Data

Where I'm stuck is I am having a hard time wrapping my head around what the loop needs to look like to go through all the class instances and get the structure to preview and then build correctly.我遇到困难的地方是,我很难通过所有 class 实例来了解循环需要看起来像 go 并让结构预览然后正确构建。 I've tried a couple while loops but they keep becoming super complex with counters and lists to keep track of where I am and it just gets unmanageable, has anybody got any ideas or pointers for a scenario like this?我已经尝试了几个while循环,但它们不断变得超级复杂,计数器和列表可以跟踪我的位置,而且它变得难以管理,有没有人对这样的场景有任何想法或指示?

Some recursion magic with pathlib.Path objects. pathlib.Path对象的一些递归魔法。 This is assuming you don't care about files but it would be quite easy to add files too and print them with different colors or something.这是假设您不关心文件,但也很容易添加文件并使用不同的 colors 或其他东西打印它们。

Be careful when running on some big directories (example /home/ ) as it will take loooong time.在一些大目录(例如/home/ )上运行时要小心,因为这需要很长时间。

from pathlib import Path
from typing import List, Union

line_tab = "    "
BOLD = '\033[1m'
END = '\033[0m'

class Directory:
    def __init__(self, path: Union[str, Path], depth: int=0, is_root: bool=True):
        self.subfolders: List["Directory"] = []
        self.depth: int = depth
        self.is_root: bool = is_root
        self.path: Path = Path(path)
        self._get_subfolders()

    def __repr__(self):
        return f"<Directory object: {self.path.absolute()}>"

    def __str__(self):
        return f"{BOLD}{self.path.name}{END}" if self.is_root else f"{line_tab*self.depth}{self.path.name}"

    def _get_subfolders(self):
        for path in self.path.iterdir():
            if path.is_dir():
                self.subfolders.append(Directory(path, depth=self.depth+1, is_root=False))

    def print_dir_structure(self):
        print(str(self))
        for subfolder in self.subfolders:
           subfolder.print_dir_structure()

test = Directory("/home/user/somedir")
test.print_dir_structure()

# You can also access subfolders like that:
test.subfolders[0].subfolders[0].subfolders[1]

# And do whatever Path object allows:
# ex. Rename subfolder at index 0 to 'foobar'
test.subfolders[0].path.rename('foobar')

pathlib is my favorite standard lib, it's really powerful: https://docs.python.org/3/library/pathlib.html pathlib 是我最喜欢的标准库,它真的很强大: https://docs.python.org/3/library/pathlib.html

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM