Introduction
In this tutorial, we will explore how to use FTP with Python to send and receive files from a server over TCP/IP connections.
To make things easier and more abstract, we will be using Python's ftplib library which provides a range of functionalities that make it easier to work with FTP. We'll see the implementation for uploading and downloading files from the server, as well as some other cool things that "ftplib" allows us to do.
What is FTP?
FTP stands for File Transfer Protocol; it is based on the client-server model architecture and is widely used. It has two channels; a command channel and a data channel. The command channel is used to control the communication and the data channel is used for the actual transmission of files. There's a wide range of things that you can do using FTP, like moving, downloading, copying files, etc. We will discuss that in a later section, along with the details on how to do it using Python.
Working with FTP in Python
Moving on, you would be happy to know that ftplib
is a built-in library that comes already installed with Python, all you need to do is import it in your script and you can start using its functions. To import it, use the following command:
from ftplib import FTP
After that, we need to initiate a connection to the FTP server that we want to open a communication link with. To do so, create an ftp
instance:
# Replace the example domain with your domain name
ftp = FTP('ftp.example.com')
The above method uses the default port, i.e. port 21, for establishing a connection with the server. Next step is to provide your login credentials, i.e. your username and password, to get access to the files on the server. You can use the following method for that:
ftp.login('your_username','your_password')
The default values for username and password are 'anonymous' and 'anonymous@', respectively. If the connection is successful, you should receive a message similar to "230 Login Successful".
Now that we have established a connection to the server, we want to navigate to the directory where we wish to do operations, i.e. get or write a file in. For that, we change the 'current working directory' using the following command:
ftp.cwd('/path/to/the/directory/')
Let's now discuss some basic examples of how to get a file from a directory or write a file to a directory. The explanation of the code is provided in the comments alongside each line of code:
file_name = 'a-filename.txt'
my_file = open(file_name, 'wb') # Open a local file to store the downloaded file
ftp.retrbinary('RETR ' + file_name, my_file.write, 1024) # Enter the filename to download
In the retrbinary
call above, the 1024 means that the file will be downloaded in blocks of 1024 bytes until the whole file is transferred.
There's one more thing that you need to do after downloading or uploading a file - close that file and also close the FTP connection that you had opened. You can do that for the above example with the following two lines of code:
ftp.quit() # Terminate the FTP connection
my_file.close() # Close the local file you had opened for downloading/storing its content
Let's now try to upload a file to the server. In addition to the commands below you would also have to rewrite the commands we used above to open an FTP connection.
file_name = 'a-filename.txt'
ftp.storbinary('STOR ' + file_name, open(file_name, rb))
In the above examples, 'rb' and 'wb' mean "read binary" and "write binary", respectively.
Additional FTP Functionalities
Now that we have discussed the implementation for the main features, let's now see some additional functionality that ftplib
provides us.
List Files and Directories
To see the files and folders in your current working directory, in list format, run the retrlines
command:
ftp.retrlines('LIST')
Make a New Directory
In order to organize your files in a certain manner, you might feel the need to create a new directory on the server, which you can do using a single line of code:
ftp.mkd('/path/for/the/directory')
The path would be the location at which you wish the new directory to be located at.
Delete a File from the Server
Removing a file on the server is fairly simple, you just have to give the name of the file as a parameter to the delete function. The operation's success or failure will be conveyed by a response message.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
ftp.delete('file_name_to_delete')
Check Current Path
To check your current path, simply run the following code:
ftp.pwd()
This command will return the absolute path to the current working directory.
Caution
It is important to note that while FTP is quite secure itself, it is not commonly used to transfer sensitive information; if you're transferring something like that then you should go for more secure options like SFTP (Secure FTP) or SSH (Secure Shell). These are the most commonly used protocols for handling sensitive data transmission.
Conclusion
In this post, we discussed what FTP is and how it works with the help of different examples. We also saw how to use Python's "ftplib" module to communicate with a remote server using FTP and saw some other functionalities that the module offers. In the end, we also discussed some more secure alternatives to FTP, such as SFTP and SSH, which are used for the transfer of sensitive information.
For more information on using FTP with Python, see the the official ftplib docs or RFC 959.