How To Make Python Check If Ftp Directory Exists?
Solution 1:
Nslt will list an array for all files in ftp server. Just check if your folder name is there.
from ftplib importFTP
ftp = FTP('yourserver')
ftp.login('username', 'password')
folderName = 'yourFolderName'if folderName in ftp.nlst():
#do needed task
Solution 2:
you can use a list. example
import ftplib
server="localhost"
user="user"
password="test@email.com"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=0for f in filelist:
if"public_html"in f:
#do something
f=1if f==0:
print"No public_html"#do your processing here
Solution 3:
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 ftplib
ftp = ftplib.FTP()
ftp.connect('ftp.somedomain.com', 21)
ftp.login()
resp = ftp.sendcmd('MLST pathname')
if'type=dir;'in resp:
# it should be a directorypass
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
Solution 4:
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
drwxrwxrwx45063 5063 4096 Sep1320:00resized
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:
defdirectory_exists_here(self, directory_name):
filelist = []
self.ftp.retrlines('LIST',filelist.append)
for f in filelist:
if f.split()[-1] == directory_name:
returnTruereturnFalse
N.B., this is inside an FTP wrapper class I wrote and self.ftp is the actual FTP connection.
Solution 5:
In 3.x nlst()
method is deprecated. Use this code:
import ftplib
remote = ftplib.FTP('example.com')
remote.login()
if'foo'in [name for name, datain list(remote.mlsd())]:
# do your stuff
The list()
call is needed because mlsd()
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.
Post a Comment for "How To Make Python Check If Ftp Directory Exists?"