1

I am working on code in which I will create folders and sub folders based on a string retrieved from the database. It's dynamic; it could be one level, two levels, or ten.

I'm trying to replace the dots with slashes and create the proper tree, but this code below won't do the job:

for x in i.publish_app.split('.'):
    if not os.path.isdir(os.path.join(settings.MEDIA_ROOT, PATH_CSS_DB_OUT) + x + '/'):
        os.mkdir(os.path.join(settings.MEDIA_ROOT, PATH_CSS_DB_OUT) + x + '/')

i.publish_app is, for example, 'apps.name.name.another.name'.

How can I do it?

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Mo J. Mughrabi
  • 6,747
  • 16
  • 85
  • 143

4 Answers4

15
os.makedirs(path[, mode])

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. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.

Straight from the docs.

Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
4

Use os.makedirs(), there is an example if you need it to behave like mkdir -p.

Community
  • 1
  • 1
klimkin
  • 573
  • 5
  • 10
1

Why aren't you just doing:

os.path.join(settings.MEDIA_ROOT, PATH_CSS_DB_OUT,x,"")

(The last ,"" is to add a \ or / at the end, but I don't think you need it to make a directory)

Manux
  • 3,643
  • 4
  • 30
  • 42
0

Starting from Python 3.5, there is pathlib.mkdir:

from pathlib import Path
path = Path(settings.MEDIA_ROOT)
nested_path = path / ( PATH_CSS_DB_OUT + x)
nested_path.mkdir(parents=True, exist_ok=True) 

This recursively creates the directory and does not raise an exception if the directory already exists.

(just as os.makedirs got an exist_ok flag starting from python 3.2 e.g os.makedirs(path, exist_ok=True))

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111