我试图写一个简单的Python脚本,将复制索引。在所有子目录(少数例外)中将TPL转换为index.html。

我在获取子目录列表时陷入了困境。


当前回答

为什么没有人提到glob?glob允许您使用unix风格的路径名展开,它是我的go to函数,几乎适用于需要查找多个路径名的所有内容。这很简单:

from glob import glob
paths = glob('*/')

请注意,glob将返回带有最后斜杠的目录(就像unix一样),而大多数基于路径的解决方案将省略最后的斜杠。

其他回答

使用Twisted的FilePath模块:

from twisted.python.filepath import FilePath

def subdirs(pathObj):
    for subpath in pathObj.walk():
        if subpath.isdir():
            yield subpath

if __name__ == '__main__':
    for subdir in subdirs(FilePath(".")):
        print "Subdirectory:", subdir

由于一些评论者问使用Twisted的库有什么好处,我将在这里稍微超出最初的问题。


分支中有一些改进的文档解释了FilePath的优点;你可能会想读一下。

More specifically in this example: unlike the standard library version, this function can be implemented with no imports. The "subdirs" function is totally generic, in that it operates on nothing but its argument. In order to copy and move the files using the standard library, you need to depend on the "open" builtin, "listdir", perhaps "isdir" or "os.walk" or "shutil.copy". Maybe "os.path.join" too. Not to mention the fact that you need a string passed an argument to identify the actual file. Let's take a look at the full implementation which will copy each directory's "index.tpl" to "index.html":

def copyTemplates(topdir):
    for subdir in subdirs(topdir):
        tpl = subdir.child("index.tpl")
        if tpl.exists():
            tpl.copyTo(subdir.child("index.html"))

上面的“subdirs”函数可以作用于任何类filepath对象。这意味着,其中包括ZipPath对象。不幸的是,ZipPath现在是只读的,但是可以扩展到支持写入。

您还可以为测试目的传递自己的对象。为了测试操作系统。在这里建议使用path-using api时,您必须处理导入的名称和隐式依赖项,并通常执行黑魔法以使您的测试正常工作。使用FilePath,你可以这样做:

class MyFakePath:
    def child(self, name):
        "Return an appropriate child object"

    def walk(self):
        "Return an iterable of MyFakePath objects"

    def exists(self):
        "Return true or false, as appropriate to the test"

    def isdir(self):
        "Return true or false, as appropriate to the test"
...
subdirs(MyFakePath(...))
def get_folders_in_directories_recursively(directory, index=0):
    folder_list = list()
    parent_directory = directory

    for path, subdirs, _ in os.walk(directory):
        if not index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)
        elif path[len(parent_directory):].count('/') + 1 == index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)

    return folder_list

下面的函数可以被调用为:

get_folders_in_directores_recurrecursive (directory, index=1) ->给出了第一层的文件夹列表

get_folders_in_directores_recurrecursive (directory) ->给出所有子文件夹

import pathlib


def list_dir(dir):
    path = pathlib.Path(dir)
    dir = []
    try:
        for item in path.iterdir():
            if item.is_dir():
                dir.append(item)
        return dir
    except FileNotFoundError:
        print('Invalid directory')

我必须提到path.py库,我经常使用它。

获取直接子目录变得如此简单:

my_dir.dirs ()

完整的工作示例是:

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

注意:my_directory仍然可以作为字符串操作,因为Path是string的子类,但提供了一堆有用的方法来操作路径

为什么没有人提到glob?glob允许您使用unix风格的路径名展开,它是我的go to函数,几乎适用于需要查找多个路径名的所有内容。这很简单:

from glob import glob
paths = glob('*/')

请注意,glob将返回带有最后斜杠的目录(就像unix一样),而大多数基于路径的解决方案将省略最后的斜杠。