High-level FTP client library (virtual file system and more)

5.1.0 · active · verified Tue Apr 14

ftputil is a high-level FTP client library for the Python programming language. It implements a virtual file system for accessing FTP servers, providing many functions similar to those in the `os`, `os.path`, and `shutil` modules. It also offers convenience functions for conditional uploads and downloads, and handles FTP clients and servers in different timezones. The current stable version is 5.1.0, released on 2024-01-06. The project follows semantic versioning, with major version changes indicating backward incompatibility. Releases are announced on its mailing list.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an FTP server, list files, download a file, create a remote directory, and upload a file using `ftputil.FTPHost`. It uses environment variables for credentials for security and easy testing.

import ftputil
import os

FTP_HOST = os.environ.get('FTP_HOST', 'ftp.example.com')
FTP_USER = os.environ.get('FTP_USER', 'your_username')
FTP_PASSWORD = os.environ.get('FTP_PASSWORD', 'your_password')

# Example: Download files from the login directory
with ftputil.FTPHost(FTP_HOST, FTP_USER, FTP_PASSWORD) as ftp_host:
    print(f"Connected to {FTP_HOST}. Current directory: {ftp_host.getcwd()}")
    names = ftp_host.listdir(ftp_host.curdir)
    for name in names:
        if ftp_host.path.isfile(name):
            print(f"Downloading {name}...")
            # remote name, local name
            ftp_host.download(name, name)

# Example: Create a new directory and upload a file
LOCAL_FILE_CONTENT = b"This is a test file.\n"
LOCAL_FILE_NAME = "local_test.txt"
REMOTE_DIR_NAME = "new_remote_dir"
REMOTE_FILE_NAME = f"{REMOTE_DIR_NAME}/remote_test.txt"

with open(LOCAL_FILE_NAME, 'wb') as f:
    f.write(LOCAL_FILE_CONTENT)

with ftputil.FTPHost(FTP_HOST, FTP_USER, FTP_PASSWORD) as ftp_host:
    print(f"Creating remote directory {REMOTE_DIR_NAME}...")
    ftp_host.makedirs(REMOTE_DIR_NAME, exist_ok=True)
    print(f"Uploading {LOCAL_FILE_NAME} to {REMOTE_FILE_NAME}...")
    ftp_host.upload(LOCAL_FILE_NAME, REMOTE_FILE_NAME)
    print("Upload complete.")

# Clean up local file
os.remove(LOCAL_FILE_NAME)

view raw JSON →