有没有办法在Python中返回当前目录中所有子目录的列表?

我知道您可以对文件执行此操作,但我需要获得目录列表。


当前回答

有很多很好的答案,但如果你来这里寻找一个简单的方法来获得所有文件或文件夹的列表。你可以利用linux和mac上提供的find操作系统,它比os.walk快得多

import os
all_files_list = os.popen("find path/to/my_base_folder -type f").read().splitlines()
all_sub_directories_list = os.popen("find path/to/my_base_folder -type d").read().splitlines()

OR

import os

def get_files(path):
    all_files_list = os.popen(f"find {path} -type f").read().splitlines()
    return all_files_list

def get_sub_folders(path):
    all_sub_directories_list = os.popen(f"find {path} -type d").read().splitlines()
    return all_sub_directories_list

其他回答

您是指直接子目录,还是树下的每个目录?

无论哪种方式,你都可以使用os。走路做这个:

os.walk(directory)

将为每个子目录生成一个元组。三元组中的第一个条目是一个目录名,因此

[x[0] for x in os.walk(directory)]

应该会递归地给出所有子目录。

注意,元组中的第二个条目是第一个位置的条目的子目录列表,所以您可以使用这个代替,但它不太可能节省太多时间。

但是,你可以使用它来给你直接的子目录:

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

或者查看已经发布的其他解决方案,使用os。Listdir和os.path。isdir,包括“如何在Python中获取所有直接子目录”中的那些。

Python 3.4在标准库中引入了pathlib模块,它提供了一种面向对象的方法来处理文件系统路径:

from pathlib import Path

p = Path('./')

# All subdirectories in the current directory, not recursive.
[f for f in p.iterdir() if f.is_dir()]

要递归地列出所有子目录,路径通配符可以与**模式一起使用。

# This will also include the current directory '.'
list(p.glob('**'))

请注意,一个*作为glob模式将非递归地包括文件和目录。为了只获取目录,可以在后面追加一个/,但这只在直接使用glob库时有效,而不是通过pathlib使用glob时:

import glob

# These three lines return both files and directories
list(p.glob('*'))
list(p.glob('*/'))
glob.glob('*')

# Whereas this returns only directories
glob.glob('*/')

因此Path('./').glob('**')匹配与glob相同的路径。一团(“* * /”,递归= True)。

Pathlib也可以通过PyPi上的pathlib2模块在Python 2.7中使用。

下面是基于@Blair Conrad的例子的几个简单函数

import os

def get_subdirs(dir):
    "Get a list of immediate subdirectories"
    return next(os.walk(dir))[1]

def get_subfiles(dir):
    "Get a list of immediate subfiles"
    return next(os.walk(dir))[2]

这应该可以工作,因为它还创建了一个目录树;

import os
import pathlib

def tree(directory):
    print(f'+ {directory}')
    print("There are " + str(len(os.listdir(os.getcwd()))) + \
    " folders in this directory;")
    for path in sorted(directory.glob('*')):
        depth = len(path.relative_to(directory).parts)
        spacer = '    ' * depth
        print(f'{spacer}+ {path.name}')

这应该列出使用pathlib库的文件夹中的所有目录。path.relative_to(目录)。Parts获取相对于当前工作目录的元素。

这是简单的递归解

import os
def fn(dir=r"C:\Users\aryan\Downloads\opendatakit"):  # 1.Get file names from directory
    file_list = os.listdir(dir)
    res = []
    # print(file_list)
    for file in file_list:
        if os.path.isfile(os.path.join(dir, file)):
                res.append(file)
        else:
            result = fn(os.path.join(dir, file))
            if result:
                res.extend(fn(os.path.join(dir, file)))
    return res


res = fn()
print(res)
print(len(res))