Search code examples
pythonpathflaskmkdir

how to os.mkdir() above current root path in python


i am running a flask project and i am looking for a way to create a directory ABOVE the path from which the current App is running. For example:

dirA -->
    dirBinA -->
        peter.py
        griffin.sh
    dirCinA -->
        index.py <--------- this is the flask app that's running
        tom.css
        dick.html
        harry.js
    dirDinA -->  <--------- this directory doesn't exist yet
        anotherDir -->
            turtle.py

i want to create a new directory anotherDir inside a new directory dirDinA from the flask app that's running in dirCinA/index.py

If I try with os.mkdir("../dirDinA/anotherDir/"), then flask says OSError: [Errno 2] No such file or directory: '../dirDinA/anotherDir'


Solution

  • In order to create a new 2-level-depth directory, you need to create it in TWO steps. For instance, if ../dirDinA doesn't yet exist, then the following command fails.

    os.mkdir("../dirDinA/anotherDir")
    

    It produces the OSError: No such file or directory, misleadingly, showing you the FULL path that you are trying to create, instead of highlighting on the ACTUAL part whose non-existence is producing the error.

    However, the following 2 step method goes well without any error

    os.mkdir("../dirDinA")
    os.mkdir("../dirDinA/anotherDir")
    

    Directory ../dirDinA needs to exist before anotherDir can be created inside it

    Thanks goes to the answer by @JimPivarski.