tags:

views:

1521

answers:

3

I'm using this script to connect to sample ftp server and list available directories:

from ftplib import FTP
ftp = FTP('ftp.cwi.nl')   # connect to host, default port (some example server, i'll use other one)
ftp.login()               # user anonymous, passwd anonymous@
ftp.retrlines('LIST')     # list directory contents
ftp.quit()

How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?

+5  A: 

you can use a list. example

import ftplib
server="localhost"
user="user"
password="[email protected]"
try:
    ftp = ftplib.FTP(server)    
    ftp.login(user,password)
except Exception,e:
    print e
else:    
    filelist = [] #to store all files
    ftp.retrlines('LIST',filelist.append)    # append to list  
    f=0
    for f in filelist:
        if "public_html" in f:
            #do something
            f=1
    if f==0:
        print "No public_html"
        #do your processing here
ghostdog74
This won't tell you if there is a *file* (rather than a directory) called `public_html`.
Vinay Sajip
if not any("public_html" in f for f in filelist): print "No public_html"else: # do somethingor:public = [f for f in filelist if "public_html" in f]if not public: print "No public_html"else: for f in public: # Do something
hughdbrown
A: 

thanks, but where do i enter code that will be executed if there's no public_html? got a little lost in it

edit: Perfect. Exactly what I needed. Thanks.

I would vote for your answer but I don't have enough rep ;)

Phil
please see edit
ghostdog74
A: 

The examples attached to ghostdog74's answer have a bit of a bug: the list you get back is the whole line of the response, so you get something like

drwxrwxrwx    4 5063     5063         4096 Sep 13 20:00 resized

This means if your directory name is something like '50' (which is was in my case), you'll get a false positive. I modified the code to handle this:

def directory_exists_here(self, directory_name):
    filelist = []
    self.ftp.retrlines('LIST',filelist.append)
    for f in filelist:
        if f.split()[-1] == directory_name:
            return True
    return False

N.B., this is inside an FTP wrapper class I wrote and self.ftp is the actual FTP connection.

Tom