Skip to main content
 首页 » 编程设计

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

2025年05月04日21jillzhang

我正在编写代码,其中我将根据从数据库中检索到的字符串创建文件夹和子文件夹。它是动态的;它可以是一级、二级或十级。

我正在尝试用斜杠替换点并创建正确的树,但下面的代码无法完成这项工作:

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 是 'apps.name.name.another.name'。

我该怎么做?

请您参考如下方法:

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.

直接来自 the docs .