2012-05-17 2 views
8

python에서 ftp를 통해 파일을 전송하는 데 pycurl을 사용하고있었습니다. 필자는 원격 서버에 누락 된 디렉토리를 자동으로 만들 수 있습니다 :ftplib storbinary에서 누락 된 디렉토리 만들기

c.setopt(pycurl.FTP_CREATE_MISSING_DIRS, 1) 

어떤 이유로 ftplib로 전환해야합니다. 그러나 나는 여기에 어떻게 해야할지 모르겠다. 거기에 storbinary 함수를 추가 할 수있는 옵션이 있습니까? 또는 수동으로 디렉토리를 만들어야합니까?

답변

9

FTP_CREATE_MISSING_DIRS는 컬 작업입니다 (added here). ftplib을 사용하여 수동으로해야한다는 생각이 들지만 나는 틀린 것으로 입증되기를 원합니다, 누구?

나는 다음과 같은 것을 할 거라고 : (테스트되지 않은, 그리고 ftplib.all_errors를 잡을 필요)

ftp = ... # Create connection 

# Change directories - create if it doesn't exist 
def chdir(dir): 
    if directory_exists(dir) is False: # (or negate, whatever you prefer for readability) 
     ftp.mkd(dir) 
    ftp.cwd(dir) 

# Check if directory exists (in current location) 
def directory_exists(dir): 
    filelist = [] 
    ftp.retrlines('LIST',filelist.append) 
    for f in filelist: 
     if f.split()[-1] == dir and f.upper().startswith('D'): 
      return True 
    return False 

을 또는이 같은 directory_exists을 할 수있는 : (열심히 조금 읽을?)

# Check if directory exists (in current location) 
def directory_exists(dir): 
    filelist = [] 
    ftp.retrlines('LIST',filelist.append) 
    return any(f.split()[-1] == dir and f.upper().startswith('D') for f in filelist) 
+1

고마워요. 정확히 내가 찾던 것이 아니었지만 좋은 대답이었습니다. Thanx;) – AliBZ

+1

아니요, 수동으로하지 않아도됩니다. 대신'ftputil' 패키지에서'makedirs' 메소드를 호출 할 수 있습니다. – xApple

4

@Alex L의 답변에 댓글을 달아 보았습니다.하지만 너무 길었습니다. 도중에 디렉토리를 만들려면 디렉토리를 변경할 때 재귀 적으로 내려야합니다. 예 :

def chdir(ftp, directory): 
    ch_dir_rec(ftp,directory.split('/')) 

# Check if directory exists (in current location) 
def directory_exists(ftp, directory): 
    filelist = [] 
    ftp.retrlines('LIST',filelist.append) 
    for f in filelist: 
     if f.split()[-1] == directory and f.upper().startswith('D'): 
      return True 
    return False 

def ch_dir_rec(ftp, descending_path_split): 
    if len(descending_path_split) == 0: 
     return 

    next_level_directory = descending_path_split.pop(0) 

    if not directory_exists(ftp,next_level_directory): 
     ftp.mkd(next_level_directory) 
    ftp.cwd(next_level_directory) 
    ch_dir_rec(ftp,descending_path_split) 
6

는 나는 이전 게시물의 일종의하지만 난 그냥이 필요하고 매우 간단한 함수를 내놓았다 알고있다. 나는 파이썬에 익숙하지 않기 때문에 어떤 피드백이라도 고맙게 생각한다.

from ftplib import FTP 

ftp = FTP('domain.com', 'username', 'password') 

def cdTree(currentDir): 
    if currentDir != "": 
     try: 
      ftp.cwd(currentDir) 
     except IOError: 
      cdTree("/".join(currentDir.split("/")[:-1])) 
      ftp.mkd(currentDir) 
      ftp.cwd(currentDir) 

사용 예 :

cdTree("/this/is/an/example") 
+2

아주 좋은! 'dir'은 비단뱀입니다. 변수 이름을 바꾸고 싶을 수도 있습니다 ... 특정 예외를 잡기를 원합니다. 모두 – xApple

+0

xApple에게 감사드립니다. 나는 'dir'을 교체하고 IOError 예외 만 잡으라는 제한을 가했다. – lecnt

+0

'dir' 변수의 인스턴스를 바꾸는 것을 잊었다 고 생각합니다. – xApple

0

경로에 누락 된 모든 폴더를 생성합니다이 코드 :

... 

def chdir(ftp_path, ftp_conn): 
    dirs = [d for d in ftp_path.split('/') if d != ''] 
    for p in dirs: 
     print(p) 
     check_dir(p, ftp_conn) 


def check_dir(dir, ftp_conn): 
    filelist = [] 
    ftp_conn.retrlines('LIST', filelist.append) 
    found = False 

    for f in filelist: 
     if f.split()[-1] == dir and f.lower().startswith('d'): 
      found = True 

    if not found: 
     ftp_conn.mkd(dir) 
    ftp_conn.cwd(dir) 

if __name__ == '__main__': 
    ftp_conn = ... # ftp connection 
    t = 'FTP/for_Vadim/1/2/3/' 

    chdir(t, ftp_conn) 

없는 DIRS

를 경로에있는 모든 DIRS을 확인하고 생성합니다이 코드 전에 "FTP/for_Vadim /" "FTP/for_Vadim/1/2/3 /"뒤에

관련 문제