How to make Python check if ftp directory exists?

2019-03-24 17:19发布

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?

标签: python ftp
7条回答
叼着烟拽天下
2楼-- · 2019-03-24 17:52

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 
查看更多
贪生不怕死
3楼-- · 2019-03-24 17:52

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.

查看更多
forever°为你锁心
4楼-- · 2019-03-24 17:54

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

查看更多
▲ chillily
5楼-- · 2019-03-24 17:59

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, data in 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.

查看更多
孤傲高冷的网名
6楼-- · 2019-03-24 18:06

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.

import ftplib
server="localhost"
user="user"
uploadToDir="public_html"
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('NLST',filelist.append)    # append to list  
    num=0
    for f in filelist:
        if f.split()[-1] == uploadToDir:
            #do something
            num=1
    if num==0:
        print "No public_html"
        #do your processing here

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.

查看更多
做自己的国王
7楼-- · 2019-03-24 18:11

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=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
查看更多
登录 后发表回答