Create missing directories in ftplib storbinary

后端 未结 6 847
傲寒
傲寒 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:47

    I'm using something like this (without cwd):

    # -*- coding:utf-8 -*-
    
    from ftplib import FTP, error_perm
    
    
    def createDirs(ftp, dirpath):
        """
        Create dir with subdirs.
    
        :param ftp:     connected FTP
        :param dirpath: path (like 'test/test1/test2')
    
        :type ftp:      FTP
        :type dirpath:  str
        :rtype:         None
    
        """
    
        dirpath = dirpath.replace('\\', '/')
        tmp = dirpath.split('/')
        dirs = []
    
        for _ in tmp:
            if len(dirs) == 0:
                dirs.append(_)
                continue
    
            dirs.append(dirs[-1] + '/' + _)
    
        for _ in dirs:
            try:
                ftp.mkd(_)
            except error_perm as e:
                e_str = str(e)
                if '550' in e_str and 'File exists' in e_str:
                    continue
    
    
    if __name__ == '__main__':
        # init ftp
        createDirs(ftp=ftp, dirpath='test/1/2/3')
    

提交回复
热议问题