Trusted answers to developer questions

What is the FTP module in Python?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

Press + to interact
import ftplib
ftp = 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.

Press + to interact
import ftplib
ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")
# The .dir() function gets the directories on the server
files = 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 /pub
files = ftp.dir()
print(files)
# The .pwd() function gets the directory that we are in
current_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.

Press + to interact
import ftplib
ftp = 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 file
filename='robots.txt'
ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
ftp.quit()

RELATED TAGS

python

CONTRIBUTOR

Mohammad Razi ul Haq
Did you find this helpful?