2017-12-06 7 views
0

私の目的は、ディレクトリとサブディレクトリに対応するリストから関数を作成することです。ディレクトリと無制限のサブディレクトリを作成する関数

たとえば、 'reports/English'は 'reports'ディレクトリのサブディレクトリ 'English'に対応します。私はフォルダに自分自身を失うことへの恐怖のうち、機能os.chdirを使用したくない

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

は、ここに私の機能です。私がしなければ

lst_1 = 

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

:このリストを検討し、そう

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

:私は再帰関数を行うにはしたいと思い

は、私はこれを試してみました

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

しかし、私はディレクトリと1つのsub_directoryに限られています。 私の関数が3つのまたは4のサブディレクトリを処理することは、このようなものを作成することができるように、私がしたい:

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

誰もがアイデアを持っていますか?

ありがとうございました!

+0

「動作しない」とはどういう意味ですか?それは何ですか? – glibdud

+0

あなたは['os.makedirs()'](https://docs.python.org/3/library/os.html#os.makedirs)を探していますか? – glibdud

+0

私の投稿の漠然としたことを申し訳なく思っていますが、今はもっと明白です。 – Manoa

答えて

0

あなたは、必ずしも単純なディレクトリの散歩を再帰を必要はありません。もちろん

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はプラットフォームの違いに対応するのに十分です)。

関連する問題