递归文件走仅向下深入一个深度

Joh*_* IV 0 python

我正在尝试为可以沿着目录走下去并返回所有文件的赋值创建代码

我在使用多级文件夹时遇到问题,例如

folder1
---> folder2
-------> foo.txt

我有以下代码

def find_larger(path, max_n_results=10):
    files = []
    print(path)
    path_files = os.listdir(path)
    for file in path_files:
        if os.path.isdir(file):
            files += find_larger(os.path.join(path, file))
        files.append(file)
    return files

print(find_larger('.'))
Run Code Online (Sandbox Code Playgroud)

但是,如果我要运行该代码,我会得到以下结果

[folder1,folder2]

我已经完成了这是一个调试器,程序没有检测到第二个目录实际上是一个目录.

如何让程序一直遍历目录.

注意,我不允许用户os.walk

Mar*_*ers 5

os.path.isdir()采取完整的路径,你只给它相对的名称.首先创建路径,然后测试:

def find_larger(path, max_n_results=10):
    files = []
    print(path)
    path_files = os.listdir(path)
    for file in path_files:
        subpath = os.path.join(path, file)
        if os.path.isdir(subpath):
            files += find_larger(subpath)
        files.append(subpath)
    return files
Run Code Online (Sandbox Code Playgroud)

但是,你在这里重新发明一个轮子,只需使用该os.walk()功能列出目录内容:

def find_larger(path, max_n_results=10):
    files = []
    print(path)
    for dirpath, dirnames, filenames in os.walk(path):
        files += (os.join(dirpath, filename) for filename in filenames)
    return files
Run Code Online (Sandbox Code Playgroud)