Python Requests: Download a File from an FTP Server

Updated: January 2, 2024 By: Guest Contributor Post a comment

Introduction

Learn how to use Python to download files from an FTP server with practical code examples ranging from the basics to more advanced techniques.

Establishing FTP Connection

The first step in downloading a file from an FTP server using Python is to establish a connection. Python provides the ftplib module, which comes with a set of classes and methods that make it easy to communicate with an FTP server.

from ftplib import FTP

# Connect to the FTP server
ftp = FTP('ftp.example.com')
ftp.login(user='username', passwd='password')

Use the FTP class to create an FTP connection object, then call the login method with the necessary credentials.

Downloading a Single File

Once connected, you can download files using the retrbinary or retrlines methods, depending on the file type.

with open('local-file.txt', 'wb') as local_file:
    ftp.retrbinary('RETR remote-file.txt', local_file.write)

This code snippet opens a local file in binary write-mode and downloads a text file from the server using the retrbinary FTP command.

Handling Directories

To download files from specific directories, first navigate to the directory using the cwd method.

ftp.cwd('/path/to/directory/')
# Proceed with file download

This command changes the current working directory on the FTP server, allowing you to access and download files within it.

Error Handling

When downloading files, it’s important to handle any potential errors such as connection issues or file not found errors.

try:
    with open('local-file.txt', 'wb') as local_file:
        ftp.retrbinary('RETR remote-file.txt', local_file.write)
except ftplib.error_perm as e:
    print(f'Error: {e}')
finally:
    ftp.quit()

This code uses a try block to catch any permission errors during the download, and assures that the FTP connection is properly closed with ftp.quit().

Advanced Usage: ftputil

For more advanced users, the ftputil library offers high-level operations on FTP servers, like working with files and directories in a more Pythonic way.

import ftputil

with ftputil.FTPHost('ftp.example.com', 'username', 'password') as host:
    host.download('remote-file.txt', 'local-file.txt')

This example uses the FTPHost object’s context manager to automatically handle connectivity and downloading of files with simple method calls.

Automating Multiple File Downloads

You can also automate the process of downloading multiple files using loops and pattern matching.

filenames = ftp.nlst()  # Get list of files in the current directory
for filename in filenames:
    if filename.endswith('.txt'):
        with open(filename, 'wb') as local_file:
            ftp.retrbinary(f'RETR {filename}', local_file.write)

This code retrieves a list of filenames in the current directory and downloads each one ending with ‘.txt’.

Conclusion

This tutorial provided insights into downloading files from an FTP server using Python, from establishing a connection, handling files and directories, to automating downloads. While ftplib offers basic FTP functionalities, tools like ftputil can enhance the experience with their user-friendly approach.