Parse return value from dir() function : ftp « Network « Python Tutorial






from ftplib import FTP

class DirEntry:
    def __init__(self, line):
        self.parts = line.split(None, 8)
        
    def isvalid(self):
        return len(self.parts) >= 6

    def gettype(self):
        return self.parts[0][0]

    def getfilename(self):
        if self.gettype() != 'l':
            return self.parts[-1]
        else:
            return self.parts[-1].split(' -> ', 1)[0]

    def getlinkdest(self):
        if self.gettype() == 'l':
            return self.parts[-1].split(' -> ', 1)[1]
        else:
            raise RuntimeError, "getlinkdest() called on non-link item"

class DirScanner(dict):
    def addline(self, line):
        obj = DirEntry(line)
        if obj.isvalid():
            self[obj.getfilename()] = obj

f = FTP('ftp.kernel.org')
f.login()

f.cwd('/pub/linux/kernel')
d = DirScanner()
f.dir(d.addline)

print "%d entries:" % len(d.keys())
for key, value in d.items():
    print "%s: type %s" % (key, value.gettype())

f.quit()








21.24.ftp
21.24.1.Using Python to Fetch Files from an FTP Server
21.24.2.Interactive FTP Example
21.24.3.FTP Download Example
21.24.4.Binary file download
21.24.5.ASCII file download
21.24.6.Binary file upload
21.24.7.Binary file download 2
21.24.8.Basic FTP connection
21.24.9.File dir() example
21.24.10.Parse return value from dir() function
21.24.11.FTP nlst example
21.24.12.nlst() with file/directory detection example