How to make Python check if ftp directory exists? How to make Python check if ftp directory exists? python python

How to make Python check if ftp directory exists?


Nslt will list an array for all files in ftp server. Just check if your folder name is there.

from ftplib import FTP ftp = FTP('yourserver')ftp.login('username', 'password')folderName = 'yourFolderName'if folderName in ftp.nlst():    #do needed task 


you can use a list. example

import ftplibserver="localhost"user="user"password="test@email.com"try:    ftp = ftplib.FTP(server)        ftp.login(user,password)except Exception,e:    print eelse:        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


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

250-Listing "/home/user": modify=20131113091701;perm=el;size=4096;type=dir;unique=813gc0004; /250 End MLST.

Translated into python that should be something along these lines:

import ftplibftp = ftplib.FTP()ftp.connect('ftp.somedomain.com', 21)ftp.login()resp = ftp.sendcmd('MLST pathname')if 'type=dir;' in resp:    # it should be a directory    pass

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