1 min read

Python Ftplib Module

The ftplib module defines the class FTP and some related items. It implements the client side of the FTP protocol.

Importing the Module

import ftplib

Connecting to an FTP Server

from ftplib import FTP

ftp = FTP('ftp.debian.org')
ftp.login()

Listing Files

You can list the files in the current directory using retrlines().

ftp.retrlines('LIST')

Downloading Files

To download a file, use retrbinary().

filename = 'README'

with open(filename, 'wb') as fp:
    ftp.retrbinary('RETR ' + filename, fp.write)

Uploading Files

To upload a file, use storbinary().

filename = 'myfile.txt'

with open(filename, 'rb') as fp:
    ftp.storbinary('STOR ' + filename, fp)

Quitting

ftp.quit()

programming/python/python