列出在中创建的所有目录os.makedirs公司()

2024-04-26 02:54:12 发布

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

os.makedirs(path)递归地创建所有不存在的目录

有没有办法打印所有新创建的目录。 说如果:

path = '/tmp/path/to/desired/directory/a/b/c'

并且/tmp/path/to/desired/directory已经存在,那么它应该返回:

/tmp/path/to/desired/directory/a
/tmp/path/to/desired/directory/a/b
/tmp/path/to/desired/directory/a/b/c

输入是/tmp/path/to/desired/directory/a/b/c,所以我不确定存在哪一级目录,所以我不能使用walk。在本例中,/tmp/path/to/desired/可能已经存在或不存在。你知道吗

我不是在找os.步行或列出子目录。我只寻找在os.makedirs()期间创建的新目录。输入路径不是静态路径。它可以变化,所以我不能去检查它的子目录列表或时间戳。我需要遍历整个文件系统


Tags: topath路径目录列表os静态directory
1条回答
网友
1楼 · 发布于 2024-04-26 02:54:12

在执行makedirs调用之前,可以检查路径的每个级别是否存在:

path = '/tmp/path/to/desired/directory/a/b/c'
splitted_path = path.split('/')
subpaths = ['/'.join(splitted_path[:i]) for i in range(2,len(splitted_path)+1)]
subpaths_iter = iter(subpaths)
for subpath in subpaths_iter:
    if not os.path.exists(subpath):
        newly_created = [subpath] + list(subpaths_iter)
        os.makedirs(path)
        break
else:
    print('makedirs not needed because the path already exists')

subpaths列表如下:

['/tmp', '/tmp/path', '/tmp/path/to', '/tmp/path/to/desired', '/tmp/path/to/desired/directory', '/tmp/path/to/desired/directory/a', '/tmp/path/to/desired/directory/a/b', '/tmp/path/to/desired/directory/a/b/c']

如果您还想检查/,您可能需要调整它。你知道吗

相关问题 更多 >