1

os.makedirs(path) creates recursively all non existing directories

Is there a way to print all the newly created directories. Say if:

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

and /tmp/path/to/desired/directory already exists then it should return:

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

Input is /tmp/path/to/desired/directory/a/b/c so I am not sure till what level directories are existing, so I cannot use walk. Here in this example /tmp/path/to/desired/ may be already existing or not.

I am not looking for os.walk or list subdirectories. I am looking for only new directories created intermediately while os.makedirs(). The input path is NOT a static one. It can be varied so I cannot go and check list of sub directories in it or the timestamp. I need to traverse entire filesystem then

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
user3294904
  • 444
  • 8
  • 26

1 Answers1

1

Before performing the makedirs call you can check for each level of the path whether it exists or not:

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

The subpaths list is the following:

['/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']

You may want to tweak it if you want to also check for just /.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231