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

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


当前回答

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')

使用pathlib的一行代码:

list_subfolders_with_paths = [p for p in pathlib.Path(path).iterdir() if p.is_dir()]

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

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

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

import os

获取目录下的(全路径)直接子目录:

def SubDirPath (d):
    return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])

获取最新(latest)子目录:

def LatestDirectory (d):
    return max(SubDirPath(d), key=os.path.getmtime)

我只是写了一些代码来移动vmware虚拟机,最终使用os。路径和shutil来完成子目录之间的文件复制。

def copy_client_files (file_src, file_dst):
    for file in os.listdir(file_src):
            print "Copying file: %s" % file
            shutil.copy(os.path.join(file_src, file), os.path.join(file_dst, file))

它不是特别优雅,但确实有用。