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

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


当前回答

选中“获取当前目录中所有子目录的列表”。

下面是Python 3的版本:

import os

dir_list = next(os.walk('.'))[1]

print(dir_list)

其他回答

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

这里有一种方法:

import os
import shutil

def copy_over(path, from_name, to_name):
  for path, dirname, fnames in os.walk(path):
    for fname in fnames:
      if fname == from_name:
        shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))


copy_over('.', 'index.tpl', 'index.html')
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']

选中“获取当前目录中所有子目录的列表”。

下面是Python 3的版本:

import os

dir_list = next(os.walk('.'))[1]

print(dir_list)