Create missing directories in ftplib storbinary

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

    FTP_CREATE_MISSING_DIRS is a curl operation (added here). I'd hazard a guess that you have to do it manually with ftplib, but I'd love to be proven wrong, anyone?

    I'd do something like the following: (untested, and need to catch 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
    

    Or you could do directory_exists like this: (a bit harder to read?)

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

提交回复
热议问题