What is the FTP module in Python?
File Transfer Protocol (FTP) is a standard network protocol for the transfer of files to and from the server. Python has a module called ftplib that allows the transfer of files through the FTP protocol.
The ftplib module allows us to implement the client side of the FTP protocol, and it allows users to connect to servers in order to send and receive files.
Connecting to a FTP server
The following code demonstrates how to connect to an FTP server and make an instance of the class.
We will connect to a publicly available FTP server – the getwelcome() function displays the initial message sent by the server on connection.
import ftplibftp = ftplib.FTP("ftp.nluug.nl")ftp.login("anonymous", "ftplib-example-1")print(ftp.getwelcome())
Listing files and directories
We can see the files and directories available on the server. The module also provides us with commands to list our current directory and change the current directory that we are in.
import ftplibftp = ftplib.FTP("ftp.nluug.nl")ftp.login("anonymous", "ftplib-example-1")# The .dir() function gets the directories on the serverfiles = ftp.dir()print(files)# The .cwd() function displays the current working directory# we are in.print("Files in the /pub/ directory")ftp.cwd('/pub/') #change directory to /pubfiles = ftp.dir()print(files)# The .pwd() function gets the directory that we are incurrent_directory = ftp.pwd()print("Current directory:", current_directory)
Downloading a text file through FTP
We can use the FTP module to download files. The current pub directory that we are in has a robots.txt that we will retrieve in our code using the retrbinary() function. The code saves the file on our local computer and then closes the connection using the .quit() function.
import ftplibftp = ftplib.FTP("ftp.nluug.nl")ftp.login("anonymous", "ftplib-example-1")ftp.cwd('/pub/') #change directory to /pub/files = ftp.dir()print(files)# Downloading the robots.txt filefilename='robots.txt'ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)ftp.quit()