Python获取当前目录下的子目录

在Python中,我们经常需要处理文件和文件夹的操作。有时候我们需要获取当前目录下的子目录,以便进一步处理和分析。本文将介绍如何使用Python来获取当前目录下的子目录,并提供了相应的代码示例。

获取当前目录

在开始之前,我们首先需要了解如何获取当前目录。在Python中,我们可以使用os模块来获取当前目录的路径。具体的代码如下所示:

import os

current_dir = os.getcwd()
print("当前目录:", current_dir)

运行以上代码,将会输出当前目录的路径。

获取子目录

有了当前目录的路径,我们就可以使用os模块来获取当前目录下的子目录。os模块提供了一个listdir()函数,用于返回指定路径下的所有文件和目录的名称列表。我们只需要过滤出目录即可。具体的代码如下所示:

import os

current_dir = os.getcwd()
subdirectories = [name for name in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, name))]

print("子目录列表:", subdirectories)

运行以上代码,将会输出当前目录下的所有子目录的名称列表。

递归获取子目录

上述的方法只能获取当前目录下的直接子目录,如果我们需要获取当前目录下的所有子目录,包括子目录的子目录,我们可以使用递归的方式。具体的代码如下所示:

import os

def get_subdirectories(directory):
    subdirectories = []
    for name in os.listdir(directory):
        path = os.path.join(directory, name)
        if os.path.isdir(path):
            subdirectories.append(path)
            subdirectories.extend(get_subdirectories(path))
    return subdirectories

current_dir = os.getcwd()
all_subdirectories = get_subdirectories(current_dir)

print("所有子目录:", all_subdirectories)

运行以上代码,将会输出当前目录下的所有子目录的路径列表。

总结

通过使用Python中的os模块,我们可以轻松获取当前目录下的子目录。通过递归的方式,我们还可以获取当前目录下的所有子目录。这对于文件和文件夹的处理和分析非常有用。希望本文能够帮助你更好地使用Python来处理文件和文件夹。