Python ftp only lists directories, not files

I would like to list all the directories in the ftp directory and then enter each of them. The problem is that my code also contains a list of files and also tries to enter them.

  • Is there a way to get the return value from the ftp.cwd method?
  • Is there a way to get only the directory name in the first place, or is there a better way to do what I want.

Here is the code I'm using now:

    from ftplib import FTP
    ftp = FTP('ftp.overtherainbow.com')
    ftp.login()
    for name in ftp.nlst():
        print "listing: " + name
        ftp.cwd(name)
        ftp.retrlines('LIST')
        ftp.cwd('../')
+3
source share
4 answers

FTP protocol cannot distinguish between directories and files (as for listing). I think the best option would be either attempt and failure

try:
    ftp.cwd(name)
except ftplib.error_perm as detail:
    print("It probably not a directory:", detail)

. , . ...

+4

Python 3.3 (mlsd): http://docs.python.org/3/library/ftplib.html#ftplib.FTP.mlsd

ftp.nlst ftp.dir " 3.3: mlsd().

+2

It's a little ugly, but ftplibit seems not very easy to use.

>>> x=[]
>>> ftp.dir('-d','*/',lambda L:x.append(L.split()[-1]))
>>> x
['access-logs/', 'etc/', 'mail/', 'perl/', 'proxy/', 'public_ftp/', 'public_html/', 'subversion/', 'tmp/', 'web/', 'www/']
+1
source

This worked for me:

def get_current_dir_subdirs(self):
    ret = []
    self.ftp.dir("",ret.append)
    ret = [x.split()[-1] for x in ret if x.startswith("d")]
    return ret 
0
source

All Articles