FTP in Python

The File Transfer Protocol (FTP) is used to exchange files between comput­ers on a network. It provides the same sort of interface to data on a distance com­puter as would be expected from a file system on a desktop. It can copy a file in either direction, but can also change directories, list the directory contents, and perform other useful operations. This again presumes that the rules set up by the FTP interface are followed.

Having just seen the communication requirements for sending and receiving email, it should be possible to predict the way that FTP operates. A connection has to be made to a remote computer, and some form of authentication takes place. The client (the program that established the connection) now send a set of commands to the server, which reads and processes them. Then, finally, the client terminates the connection.

The commands that can be processed by an FTP server include listing the contents of the directory (LIST), changing the working directory (CWD), retriev­ing a file (RETR), and sending or storing a file (STOR). These are sent across the network as strings and represent raw FTP commands, and take place at a low level of abstraction in the system. Higher level commands are implemented as specific methods in the FTP class offtplib. For example, there is a command named PWD that displays the name of the current remote directory. FTP offers a function that sends this command:

FTP.pwd()

Doing the same thing by sending the command directly uses the sendcmd() method of FTP, and it passes the command as a string:

ftp.sendcmd(“PWD”)

There is a difference to the programmer. The pwd() method returns the string that represents the directory, whereas when the text command is sent, the return value is the string that the FTP system returned, which is something like

257 “/” is the current directory

1. Example: Download and Display the

README File from an FTP Site

The site chosen for the example belongs to NASA, but any ftp site will work. The connection and authentication steps are as follows:

from ftplib import FTP

ftp = FTP(“ftp.hq.nasa.gov”)  # Please don’t always use NASA

ftp.login()                   # Select a different site.

The login step is interesting because there are no parameters given. This is an anonymous FTP connection, which is common for sites that offer things for download. The default login when using the login() method is a user ID of “anonymous” and a password, if one is requested, of “anonymous.” It is also pos­sible to specify an ID and password if the user has them:

ftp.login(“myuserid”, “mypassword”)

The login() function returns the site’s welcome message, which is a string that can be ignored.

The example is supposed to download the file named README and display it. The method retrlines() can do this, because it is a text file. If it were a binary file, like an MP3 or JPG file, then the retrbinary() method would be used in­stead. The first parameter to retrlines() is a command. To retrieve a file the com­mand is the keyword RETR followed by the file name. The simplest version is

ftp.retrlines(‘RETR README’)

which displays the text from the file on the screen. That’s what was wanted, but the method can do more. If a function name is passed as the second parameter, then that function is called for with every line of text, and will pass that line as a parameter. To illustrate this, consider a simple function that takes a string and prints each line, looking for “\\n” characters. The function is

def myprint (ss):

s = str(ss) # Sometimes the parameter ss is type byte.

x = s.split(“\\n”)

for i in range (0, len(x)):

print (x[i])

A call to retrlines() could be as follows:

ftp.retrlines(‘RETR README’, myprint)

or even

ftp.retrlines(‘RETR README’, print)

to use the standard print() function. Of course, any function that takes a string parameter could be passed. To save the README file as a local file, for example,

ftp.retrlines(‘RETR README’, open(‘README’, ’w’j.write)

writes the file to a local one named README, but it lacks the end-of-line char­acters.

Binary files use retrbinary(), and it has the same form as retrlines(). How­ever, the second parameter, the function, must be passed, because binary files cannot be sent to the screen. Downloading and saving an image file might be done as follows:

ftp.retrbinary(‘RETR orion.jpg, open(‘orion.jpg, ‘wb’). write)

The session would end by logging out:

ftp.quit()

Uploading a file, that is moving a file from a desktop to a site on the Inter­net, used the method storlines() for text and storbinary() for binary files. For example,

f = open (“message.txt”, “rb”)

ftp.storlines (“STOR message.txt”, f)

The method copies lines from the local file to the remote one. The file to be copied is open in “rb” mode. For a binary example, assume there is an image:

f = open (“image.jpg”, “rb”)

ftp.storbinary (“STOR image.jpg”, f)

session.storbinary(‘STOR kitten.jpg’, file)    # send the file

Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *