2017-12-06 1 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 

을하지만, 나는 디렉토리와 단 하나의 하위 디렉토리로 제한되어있다. 내 기능은 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은 플랫폼 차이를 다루기에 충분합니다).

관련 문제