2

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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks mate. I don't know how I missed that, Python is really something :)
4

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

Comments

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)

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.