nested directory in Python


Problem:


Traceback (most recent call last):

  File "makesubdir.py", line 3, in <module>

    path.mkdir()

  File "/home/xxxx/yyyyy/lib/python3.7/pathlib.py", line 1230, in mkdir

    self._accessor.mkdir(self, mode)

FileNotFoundError: [Errno 2] No such file or directory: '/home/xxxxx/yyyyyy/zzzzDirectory'



Solution:



Creating a Nested Directory with pathlib


Instead of below code:


Path.mkdir(mode=0o777, parents=False, exist_ok=False)


use below code that is with pathlib


from pathlib import Path 

path = Path("/home/xxxxxx/yyyyDirectory/zzzzzDir") 

try:

    path.mkdir() 

except OSError:

    print("Failed to create nested dir")

else:

    print("Nested directory created")



Pathlib library url: https://pathlib.readthedocs.io/en/pep428/

Comments