Fetching Data via FTP
The
ftplib
module is used in much the same way as
the httplib module: a single class,
FTP, provides all of the functionality.
The FTP protocol supports a variety of commands, which include such operations as logging in, navigating the filesystem, and retrieving directory listings. Let’s create an FTP session:
>>> import ftplib
>>> ftp = ftplib.FTP('ftp.python.org') # connect to host, default port
>>>Log on as an anonymous user:
>>> ftp.login('anonymous', 'your@email.address')
"230-WELCOME to python.org, the Python programming language ..."
>>>Get a directory listing:
>>> ftp.retrlines('LIST') # list directory contents
total 38
drwxrwxr-x 11 root 4127 512 Aug 28 20:23 .
...
-r--r--r-- 1 klm 1000 764 Aug 25 19:32 welcome.msg
'226 Transfer complete.'Notice there’s a file welcome.msg:
let’s download the file. Open a local file and indicate its
write method should be called to store the data:
>>> file=open("welcome.msg", "w")
>>> ftp.retrlines("retr welcome.msg", file.write)
'226 Transfer complete.'
>>> file.close()Now reopen the file and print the data:
>>> open("welcome.msg", "r").read()
"WELCOME to python.org, the Python programming language home site. ..."
>>>To retrieve a binary file (such as an executable), you could use the
method retrbinary()
; it takes the same methods as
retrlines()
, except it also allows you to specify a
block size for the transfer. In this case you should remember to open
the file itself in binary mode, as discussed in Chapter 3.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access