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

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


当前回答

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

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

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

其他回答

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

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

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

import glob
import os

def child_dirs(path):
     cd = os.getcwd()        # save the current working directory
     os.chdir(path)          # change directory 
     dirs = glob.glob("*/")  # get all the subdirectories
     os.chdir(cd)            # change directory to the script original location
     return dirs

child_dirs函数的作用是:获取一个目录的路径,并返回其中直接子目录的列表。

dir
 |
  -- dir_1
  -- dir_2

child_dirs('dir') -> ['dir_1', 'dir_2']

操作系统。在这种情况下,走路是你的朋友。

直接从文档中:

Walk()通过自顶向下或自底向上遍历目录树来生成目录树中的文件名。对于根在目录顶部的树中的每个目录(包括top本身),它会生成一个3元组(dirpath、dirnames、filename)。

我只是写了一些代码来移动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))

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

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