Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Being an FTP Client

Credit: Luther Blissett

Problem

You want to connect to an FTP server and upload or retrieve files. You might want to automate the one-time transfer of many files or automatically mirror an entire section of an FTP server.

Solution

The ftplib module makes this reasonably easy:

import ftplib

ftp = ftplib.FTP("ftp.host.com")
ftp.login(username, password)
ftp.cwd(directory)
# Retrieve a binary file to save on your disk
ftp.retrbinary('RETR '+filename, open(filename,'wb').write)
# Upload a binary file from your disk
ftp.storbinary('STOR '+filename, open(filename,'rb'))

Discussion

urllib may be sufficient for getting documents via FTP, but the ftplib module offers more functionality (including the ability to use FTP to upload files, assuming, of course, that you have the needed permission on the server in question) and finer-grained control for this specific task.

login defaults to an anonymous login attempt if you call it without arguments, but you normally pass username and password arguments. cwd changes the current directory on the server. retrbinary retrieves binary data from the server and repeatedly calls its second argument with the data. Thus, you will usually pass a file object’s write bound method as the second argument. storbinary stores binary data on the server, taking the data from its second argument, which must be a file-like object (the method calls read(N) on it). There are also the retrlines and storlines methods, which work similarly but on text data, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata