Search code examples
pythonpathlib

is there a way to create and init a dir variable in one line using pathlib?


I try to stick to pathlib to create and manipulate path but generating folders is always a pain. If I want to init a "toto" folder in a "tutu" folder and store the path in a variable I'm forced to do the following:

from pathlib import Path 

tutu = Path("tutu")
toto = tutu / "toto"
toto.mkdir()

Is there a way to generate toto variable AND init the folder in one line ?


Solution

  • You could do this:

    >>> (toto := tutu / "toto").mkdir()
    >>> toto
    PosixPath('tutu/toto')
    

    But more Pythonic would be just to define a utility function.