Foundations of Python Network Programming

(WallPaper) #1

Chapter 17 ■ Ftp


328


Notice that the file names are in a convenient format for automated processing—a bare list of file names—but
there is no extra information. Contrast the bare list of file names that you saw earlier with the output from Listing 17-8,
which uses dir():


$ python dir.py


13 entries:


-rw-r--r-- 1 (?) » (?) » » 750 Feb 14 1994 INDEX


-rw-r--r-- 1 root » bin » » 135 Feb 11 1999 README


-rw-r--r-- 1 (?) » (?) » 341303 Oct 2 1992 ephem_4.28.tar.Z


drwxr-xr-x 2 (?) » (?) » » 4096 Feb 11 1999 hawaii_scope


drwxr-xr-x 2 (?) » (?) » » 4096 Feb 11 1999 incoming


-rw-r--r-- 1 (?) » (?) » » 5983 Oct 2 1992 jupitor-moons.shar.Z


-rw-r--r-- 1 (?) » (?) » » 1751 Oct 2 1992 lunar.c.Z


-rw-r--r-- 1 (?) » (?) » » 8078 Oct 2 1992 lunisolar.shar.Z


-rw-r--r-- 1 (?) » (?) » » 64209 Oct 2 1992 moon.shar.Z


drwxr-xr-x 2 (?) » (?) » » 4096 Jan 6 1993 planetary


-rw-r--r-- 1 (?) » (?) » 129969 Oct 2 1992 sat-track.tar.Z


-rw-r--r-- 1 (?) » (?) » » 16504 Oct 2 1992 stars.tar.Z


-rw-r--r-- 1 (?) » (?) » 410650 Oct 2 1992 xephem.tar.Z


The dir() method takes a function that it calls for each line, delivering the directory listing in pieces just like
retrlines() delivers the contents of particular files. Here, you simply supply the append() method of the plain old
Python entries list.


Detecting Directories and Recursive Download

If you cannot guarantee what information an FTP server might choose to return from its dir() command, how are you
going to tell directories from normal files—an essential step when downloading entire trees of files from the server?
The only sure answer, shown in Listing 17-9, is simply to try adding a cwd() into every name that nlst()
returns and, if you succeed, conclude that the entity is a directory! This sample program does not do any actual
downloading; instead, to keep things simple (and not to flood your disk with sample data), it prints out the
directories it visits to the screen.


Listing 17-9. Trying to Recurse into Directories


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter17/recursedl.py


from ftplib import FTP, error_perm


def walk_dir(ftp, dirpath):
original_dir = ftp.pwd()

Free download pdf