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?
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.
Use os.makedirs()
, there is an example if you need it to behave like mkdir -p
.
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)
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)
)
精彩评论