简体   繁体   English

从字符串动态创建文件夹树

[英]Create folder tree dynamically from a string

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' . i.publish_app是例如'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. 与mkdir()相似,但是使所有中间级目录都包含叶子目录。 Raises an error exception if the leaf directory already exists or cannot be created. 如果叶目录已经存在或无法创建,则引发错误异常。 The default mode is 0777 (octal). 默认模式是0777(八进制)。 On some systems, mode is ignored. 在某些系统上,模式被忽略。 Where it is used, the current umask value is first masked out. 使用它时,当前的umask值将首先被屏蔽掉。

Straight from the docs . 直接来自文档

Use os.makedirs() , there is an example if you need it to behave like mkdir -p . 使用os.makedirs() ,如果您需要使其表现得像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 : 从Python 3.5开始,有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 eg os.makedirs(path, exist_ok=True) ) (就像os.makedirs从python 3.2开始有一个exist_ok标志,例如os.makedirs(path, exist_ok=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM