How to make Python check if ftp directory exists?

前端 未结 8 1823
一生所求
一生所求 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:44

    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.

提交回复
热议问题