Python目录树列表

2024-04-25 16:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

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

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')

下面是我经常使用的一个助手函数:

import os

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

你可以用

os.listdir(path)

有关参考和更多操作系统功能,请参见:

相关问题 更多 >