Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create missing directories in ftplib storbinary

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_CREATE_MISSING_DIRS, 1)

for some reasons, I have to switch to ftplib. But I don't know how to to the same here. Is there any option to add to storbinary function to do that? or I have to create the directories manually?

like image 525
AliBZ Avatar asked May 17 '12 22:05

AliBZ


People also ask

How do I create a folder on an FTP server?

The MKdir subcommand directs the FTP client to send an MKD command to the remote host FTP server to create a directory with name directory. If the server is a Communications Server for z/OS FTP server, and directory is a fully qualified MVS data set name, the server allocates a PDS or PDSE named directory.

How do I close an FTP connection in python?

The quit() method gracefully closes the FTP connection with the server. Once quit() is called, the FTP object can not be used by calling the connect() method again. The quit() method internally sends the QUIT command to the FTP server.


2 Answers

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)
like image 52
Alex L Avatar answered Sep 22 '22 20:09

Alex L


I know it's kind of an old post but I just needed this and came up with a very simple function. I'm new to Python so I'd appreciate any feedback.

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)

Usage example:

cdTree("/this/is/an/example")
like image 23
lecnt Avatar answered Sep 21 '22 20:09

lecnt