self.connection.cwd(fname) # chdir into remote dir
self.cleanDir() # clean subdirectory
self.connection.cwd('..') # chdir remote back up
self.connection.rmd(fname) # delete empty remote dir
self.dcount += 1
print('directory exited')
if name == 'main':
ftp = CleanAll()
ftp.configTransfer(site='learning-python.com', rdir='training', user='lutz')
ftp.run(cleanTarget=ftp.cleanDir)
print('Done:', ftp.fcount, 'files and', ftp.dcount, 'directories cleaned.')
Besides again being recursive in order to handle arbitrarily shaped trees, the main trick
employed here is to parse the output of a remote directory listing. The FTP nlst call
used earlier gives us a simple list of filenames; here, we use dir to also get file detail
lines like these:
C:\...\PP4E\Internet\Ftp> ftp learning-python.com
ftp> cd training
ftp> dir
drwxr-xr-x 11 5693094 450 4096 May 4 11:06.
drwx---r-x 19 5693094 450 8192 May 4 10:59 ..
-rw----r-- 1 5693094 450 15825 May 4 11:02 2009-public-classes.htm
-rw----r-- 1 5693094 450 18084 May 4 11:02 2010-public-classes.html
drwx---r-x 3 5693094 450 4096 May 4 11:02 books
-rw----r-- 1 5693094 450 3783 May 4 11:02 calendar-save-aug09.html
-rw----r-- 1 5693094 450 3923 May 4 11:02 calendar.html
drwx---r-x 2 5693094 450 4096 May 4 11:02 images
-rw----r-- 1 5693094 450 6143 May 4 11:02 index.html
...lines omitted...
This output format is potentially server-specific, so check this on your own server before
relying on this script. For this Unix ISP, if the first character of the first item on the line
is character “d”, the filename at the end of the line names a remote directory. To parse,
the script simply splits on whitespace to extract parts of a line.
Notice how this script, like others before it, must skip the symbolic “.” and “..” current
and parent directory names in listings to work properly for this server. Oddly this can
vary per server as well; one of the servers I used for this book’s examples, for instance,
does not include these special names in listings. We can verify by running ftplib at the
interactive prompt, as though it were a portable FTP client interface:
C:\...\PP4E\Internet\Ftp> python
>>> from ftplib import FTP
>>> f = FTP('ftp.rmi.net')
>>> f.login('lutz', 'xxxxxxxx') # output lines omitted
>>> for x in f.nlst()[:3]: print(x) # no. or .. in listings
...
2004-longmont-classes.html
2005-longmont-classes.html
2006-longmont-classes.html
>>> L = []
Transferring Directory Trees with ftplib | 897