python中,如何获取一个目录下所有文件的路径,包括子目录下的文件,但不包括子目录路径

In python, how to get the path to all the files in a directory, including files in subdirectories, but excluding path to subdirectories

我有一个包含文件夹和子文件夹的目录。在每个路径的末尾都有文件。我想制作一个包含所有文件路径的 txt 文件,但不包括文件夹路径。

我尝试了 Getting a list of all subdirectories in the current directory 的建议,我的代码如下所示:

import os

myDir = '/path/somewhere'

print [x[0] for x in os.walk(myDir)] 

它给出了所有元素(文件和文件夹)的路径,但我只想要文件的路径。有什么想法吗?

os.walk 方法在每次迭代中为您提供目录、子目录和文件,因此当您循环遍历 os.walk 时,您将不得不遍历文件并将每个文件与 "dir".

为了执行此组合,您要做的是在目录和文件之间执行 os.path.join

这里有一个简单的例子来帮助说明 os.walk 的遍历是如何工作的

from os import walk
from os.path import join

# specify in your loop in order dir, subdirectory, file for each level
for dir, subdir, files in walk('path'):
    # iterate over each file
    for file in files:
        # join will put together the directory and the file
        print(join(dir, file))

os.walk(路径)returns 三元组父文件夹、子目录和文件。

所以你可以这样做:

for dir, subdir, files in os.walk(path):
    for file in files:
        print os.path.join(dir, file)

如果您只想要路径,请按如下方式向您的列表理解添加过滤器:

import os

myDir = '/path/somewhere'
print [dirpath for dirpath, dirnames, filenames in os.walk(myDir) if filenames] 

这只会为包含文件的文件夹添加路径。

def get_paths(path, depth=None):
    for name in os.listdir(path):
        full_path = os.path.join(path, name)

        if os.path.isfile(full_path):
            yield full_path

        else:
            d = depth - 1 if depth is not None else None

            if d is None or d >= 0:
                for sub_path in get_paths(full_path):
                    yield sub_path