Create missing directories in ftplib storbinary

后端 未结 6 867
傲寒
傲寒 2021-02-07 11:28

I was using pycurl to transfer files over ftp in python. I could create the missing directories automatically on my remote server using:

c.setopt(pycurl.FTP_CREA         


        
6条回答
  •  星月不相逢
    2021-02-07 11:56

    I tried adding this as a comment to the @Alex L 's answer, but it was too long. You need to descend recursively when changing directory if you want to create directories on the way. E.g.

    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)
    

提交回复
热议问题