【问题标题】:Function that create a directory and an unlimited number of subdirectories创建目录和无限数量的子目录的功能
【发布时间】:2017-12-06 18:17:34
【问题描述】:

我的目标是从对应于目录和子目录的列表中创建一个函数。

例如:'reports/English'对应目录'reports'中的子目录'English'。

这是我的功能:

for i in lst:
  splitted = i.split('/')
  if not os.path.exists(destination_directory + '\\' + splitted[0]) : 
    os.mkdir(destination_directory + '\\' + splitted[0])
    os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
  else :
    os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])

我不想使用 os.chdir 函数,因为害怕在文件夹中迷失自己。

我想做一个递归函数,我试过这个:

def my_sub_function(splitted):
"""
"""
if splitted == []:
    return None

else:
    if not os.path.exists(destination_directory + '\\' + splitted[0]) : 
        os.mkdir(destination_directory + '\\' + splitted[0])
        os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
    else :
        os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
        return t1(splitted[1:])

所以,考虑一下这个列表:

lst_1 = 

['music',
 'reports/English',
 'reports/Spanish',
 'videos',
 'pictures/family',
 'pictures/party']

如果我这样做:

it will creates these directories :
.\\music
.\\reports\\English
.\\reports\\Spanish
.\\videos
.\\pictures\\family
.\\pictures\\party

但我仅限于一个目录并且只有一个子目录。 我希望我的函数能够处理 3 或 4 个子目录,以便它可以创建类似这样的内容:

.\\pictures\\family\\Christmas\\meal\\funny

有人有想法吗?

谢谢!

【问题讨论】:

  • 你能更详细地解释一下“它不起作用”是什么意思吗?它在做什么?
  • 您只是在寻找os.makedirs()吗?
  • 对不起,我的帖子含糊不清,我希望现在更明确
  • 我必须设法在没有 os.makedirs() #schoolwork 的情况下做到这一点

标签: python-3.x function recursion


【解决方案1】:

你不一定需要递归,只需要一个简单的目录遍历:

import os

def create_path(path):
    current_path = "."  # start with the current path
    segments = os.path.split(path)  # split the path into segments
    for segment in segments:
        candidate = os.path.join(current_path, segment)  # get the candidate
        if not os.path.exists(candidate):  # the path doesn't exist
            os.mkdir(candidate)  # create it
        current_path = candidate  # this is now our new path
    return current_path  # return the final path

当然,您可以使用os.makedirs() 代替为您完成这一切。无论哪种方式,您还应该检查您是否在此过程中遇到文件(因为简单的os.path.exists() 在所有情况下都不够用)并在用户无权创建目录的情况下进行错误处理。

此外,不要使用文字路径分隔符,因为它们因平台而异(尽管 CPython 通常足够聪明,可以处理平台差异)。

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多