Foundations of Python Network Programming

(WallPaper) #1

Chapter 17 ■ Ftp


326


One of the problems with the basic retrbinary() function is that, in order to use it easily, you will usually wind
up opening the file on the local end before beginning the transfer on the remote side. If your command aimed at the
remote side retorts that the file does not exist, or if the RETR command otherwise fails, then you will have to close and
delete the local file you have just created (or else wind up littering the file system with zero-length files).
With the ntransfercmd() method, by contrast, you can check for a problem prior to opening a local file.
Listing 17-6 already follows these guidelines: if ntransfercmd() fails, the exception will cause the program to terminate
before the local file is opened.


Scanning Directories

FTP provides two ways to discover information about server files and directories. These are implemented in ftplib as
the nlst() and dir() methods.
The nlst() method returns a list of entries in a given directory—all of the files and directories are inside.
However, the bare names are all that is returned. There is no other information about which particular entries are files
or are directories, on the sizes of the files present, or anything else.
The more powerful dir() function returns a directory listing from the remote. This listing is in a system-defined
format, but it typically contains a file name, size, modification date, and file type. On Unix servers, it is typically the
output of one of these two shell commands:


$ ls -l
$ ls -la


Windows servers may use the output of dir. Although the output may be useful to an end user, it is difficult for a
program to use, due to the varying output formats. Some clients that need these data implement parsers for the many
different formats that ls and dir produce across machines and operating system versions; others can only parse the
one format in use in a particular situation.
Listing 17-7 shows an example of using nlst() to get directory information.


Listing 17-7. Getting a Bare Directory Listing


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


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


from ftplib import FTP


def main():
ftp = FTP('ftp.ibiblio.org')
ftp.login()
ftp.cwd('/pub/academic/astronomy/')
entries = ftp.nlst()
ftp.quit()


print(len(entries), "entries:")
for entry in sorted(entries):
print(entry)


if name == 'main':
main()

Free download pdf