How to make Python check if ftp directory exists?

前端 未结 8 1854
一生所求
一生所求 2021-02-12 20:17

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


        
8条回答
  •  猫巷女王i
    2021-02-12 20:44

    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.

提交回复
热议问题