How to make Python check if ftp directory exists?

前端 未结 8 1830
一生所求
一生所求 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条回答
  •  死守一世寂寞
    2021-02-12 20:43

    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

提交回复
热议问题