Python中的目录树列表

612 投票
21 回答
712309 浏览
提问于 2025-04-11 09:22

我想知道怎么用Python获取一个文件夹里所有的文件和子文件夹的列表?

21 个回答

135

这是我经常使用的一个辅助函数:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]
544

你可以使用

os.listdir(path)

如果想了解更多关于操作系统的功能,可以查看以下链接:

637

这是一个遍历目录树中每个文件和文件夹的方法:

import os

for dirname, dirnames, filenames in os.walk('.'):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Advanced usage:
    # editing the 'dirnames' list will stop os.walk() from recursing into there.
    if '.git' in dirnames:
        # don't go into any .git directories.
        dirnames.remove('.git')

撰写回答