-2

How to create a multi folders with nested structure in python api in a simple way with out loops like unix command mkdir -p a/b/c/{d,e,f} seems like pathlib or os.mkdirs has no direct provision for this.

Tried in this way pathlib.Path(dest).mkdir(0o755, parents=True, exist_ok=True) but not working

STF
  • 1,485
  • 3
  • 19
  • 36
Ram Ghadiyaram
  • 28,239
  • 13
  • 95
  • 121
  • Is the ```dest``` argument to ```Path()``` actually ```"a/b/c/{d,e,f}"``` ? ```pathlib``` doesn't do brace expansion like shells do. – sj95126 Sep 17 '21 at 02:45
  • exactly is there any smarter way to achieve this like with out writing lot of code? – Ram Ghadiyaram Sep 17 '21 at 03:31
  • You could try ```braceexpand``` as mentioned [in this answer](https://stackoverflow.com/a/38485954/13843268). Other than that, you probably have to craft each path to pass to ```pathlib``` or use something like ```subprocess``` to execute the ```mkdir``` command as you would on the command line. – sj95126 Sep 17 '21 at 03:52

2 Answers2

0

This could be done in Python with Pathlib and a simple for loop

from pathlib import Path

base = Path("a/b/c")

for child in ['d', 'e', 'f']:
    (base / Path(child)).mkdir(mode=0o755, parents=True, exist_ok=True)
nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12
0
from pathlib import Path

dest = Path('a/b/c')
subdirs = ['d', 'e', 'f']

[(dest / subdir).mkdir(parents=True, exist_ok=True) for subdir in subdirs]
ArunJose
  • 1,999
  • 1
  • 10
  • 33