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?
Nslt will list an array for all files in ftp server. Just check if your folder name is there.
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
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:
N.B., this is inside an FTP wrapper class I wrote and self.ftp is the actual FTP connection.
You can send "MLST path" over the control connection. That will return a line including the type of the path (notice 'type=dir' down here):
Translated into python that should be something along these lines:
Of course the code above is not 100% reliable and would need a 'real' parser. You can look at the implementation of MLSD command in ftplib.py which is very similar (MLSD differs from MLST in that the response in sent over the data connection but the format of the lines being transmitted is the same): http://hg.python.org/cpython/file/8af2dc11464f/Lib/ftplib.py#l577
In 3.x
nlst()
method is deprecated. Use this code:The
list()
call is needed becausemlsd()
returns a generator and they do not support checking what is in them (do not have__contains__()
method).You can wrap
[name for name, data in list(remote.mlsd())]
list comp in a function of method and call it when you will need to just check if a directory (or file) exists.Tom is correct, but no one voted him up however for the satisfaction who voted up ghostdog74 I will mix and write this code, works for me, should work for you guys.
first of all if you follow ghost dog method, even if you say directory "public" in f, even when it doesnt exist it will evaluate to true because the word public exist in "public_html" so thats where Tom if condition can be used so I changed it to if f.split()[-1] == uploadToDir:.
Also if you enter a directory name somethig that doesnt exist but some files and folder exist the second by ghostdog74 will never execute because its never 0 as overridden by f in for loop so I used num variable instead of f and voila the goodness follows...
Vinay and Jonathon are right about what they commented.
you can use a list. example