Elegant way to make all dirs in a path

前端 未结 3 746
暗喜
暗喜 2021-02-04 23:58

Here are four paths:

p1=r\'\\foo\\bar\\foobar.txt\'
p2=r\'\\foo\\bar\\foo\\foo\\foobar.txt\'
p3=r\'\\foo\\bar\\foo\\foo2\\foobar.txt\'
p4=r\'\\foo2\\bar\\foo\\fo         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 00:01

    You are looking for os.makedirs() which does exactly what you need.

    The documentation states:

    Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Raises an error exception if the leaf directory already exists or cannot be created.

    Because it fails if the leaf directory already exists you'll want to test for existence before calling os.makedirs().

提交回复
热议问题