Skip to content

ftplib

The Python ftplib module implements the client side of the File Transfer Protocol (FTP), allowing Python programs to connect to FTP servers and transfer files programmatically.

Here’s a quick look at listing a directory on an FTP server:

Language: Python
from ftplib import FTP

with FTP("ftp.example.com") as ftp:
    ftp.login()
    ftp.cwd("pub")
    print(ftp.nlst())
# ['README', 'data.tar.gz', 'changelog.txt']

The module provides two classes: FTP for plain connections and FTP_TLS for connections secured with TLS.

Key Features

  • Implements RFC 959 with UTF-8 encoding support per RFC 2640
  • Supports both binary and line-mode file transfers
  • Uses passive mode by default, which works through most firewalls
  • Provides FTP_TLS for TLS-encrypted control connections and opt-in data channel encryption via prot_p()
  • Supports context manager usage for automatic connection cleanup
  • Covers directory listing, navigation, upload, download, rename, and delete operations

Frequently Used Classes and Functions

Object Type Description
ftplib.FTP Class Opens a plain FTP connection to a server
ftplib.FTP_TLS Class Opens an FTP connection secured with TLS
FTP.login() Method Authenticates with the server (defaults to anonymous login)
FTP.retrbinary() Method Downloads a file in binary mode by passing each block to a callback
FTP.storbinary() Method Uploads a file in binary mode from a file-like object
FTP.retrlines() Method Downloads a file or directory listing line by line
FTP.mlsd() Method Lists a directory in standardized format, returning filename and metadata pairs
FTP.cwd() Method Changes the working directory on the server
FTP.pwd() Method Returns the current working directory path on the server
FTP.delete() Method Deletes a file from the server
FTP.rename() Method Renames or moves a file on the server
ftplib.all_errors Tuple Contains all ftplib exception types for broad error handling

Examples

Downloading a file in binary mode:

Language: Python
from ftplib import FTP

with FTP("ftp.example.com") as ftp:
    ftp.login()
    with open("data.tar.gz", "wb") as f:
        ftp.retrbinary("RETR data.tar.gz", f.write)

Uploading a file in binary mode:

Language: Python
from ftplib import FTP

with FTP("ftp.example.com") as ftp:
    ftp.login("alice", "secret")
    with open("report.pdf", "rb") as f:
        ftp.storbinary("STOR report.pdf", f)

Connecting securely with FTP_TLS and protecting the data channel:

Language: Python
from ftplib import FTP_TLS

with FTP_TLS("ftp.example.com") as ftps:
    ftps.login("alice", "secret")
    ftps.prot_p()  # Secure the data connection
    ftps.cwd("uploads")
    with open("backup.tar.gz", "rb") as f:
        ftps.storbinary("STOR backup.tar.gz", f)

Common Use Cases

The most common tasks for ftplib include:

  • Automating scheduled file uploads to legacy FTP servers
  • Downloading archives or data feeds from public FTP mirrors
  • Mirroring remote FTP directories to a local filesystem
  • Connecting to secure FTP servers using FTP_TLS with an ssl.SSLContext

Real-World Example

The following script downloads all .csv files from a directory on an FTP server:

Language: Python Filename: ftp_download_csv.py
from ftplib import FTP, all_errors
from pathlib import Path

OUTPUT_DIR = Path("downloads")
OUTPUT_DIR.mkdir(exist_ok=True)

try:
    with FTP("ftp.example.com") as ftp:
        ftp.login()
        ftp.cwd("data/reports")
        csv_files = [name for name in ftp.nlst() if name.endswith(".csv")]
        for filename in csv_files:
            dest = OUTPUT_DIR / filename
            with open(dest, "wb") as f:
                ftp.retrbinary(f"RETR {filename}", f.write)
            print(f"Downloaded: {filename}")
except all_errors as e:
    print(f"FTP error: {e}")

Run it:

Language: Shell
$ python ftp_download_csv.py
Downloaded: sales_jan.csv
Downloaded: sales_feb.csv
Downloaded: summary.csv

The script uses nlst() to filter filenames by extension and retrbinary() to download each file into a local downloads/ directory. Wrapping the session in all_errors catches any connection, authentication, or protocol failure in one place.

Tutorial

Python's urllib.request for HTTP Requests

In this tutorial, you'll be making HTTP requests with Python's built-in urllib.request. You'll try out examples and review common errors encountered, all while learning more about HTTP requests and Python in general.

intermediate api web-dev web-scraping

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 15, 2026