Web Basics
This section gives a rather brief overview of selected Python libraries for working with
web technologies and protocols. Several topics, like the handling of email functionality
with Python, are not touched upon.
ftplib
The File Transfer Protocol (FTP) is, as the name suggests, a protocol to transfer files
over the Web.
[ 50 ]
Python provides a dedicated library to work with FTP called ftplib:
In [ 1 ]: import ftplib
import numpy as np
In what follows, we will connect to an FTP server, log in, transfer a file to the server,
transfer it back to the local machine, and delete the file on the server. First, the connection:
In [ 2 ]: ftp = ftplib.FTP(‘quant-platform.com’)
Not every FTP server is password protected, but this one is:
In [ 3 ]: ftp.login(user=‘python’, passwd=‘python’)
Out[3]: ‘230 Login successful.’
To have a file that we can transfer, we generate a NumPy ndarray object with some random
data and save it to disk:
In [ 4 ]: np.save(‘./data/array’, np.random.standard_normal(( 100 , 100 )))
For the FTP file transfer to follow, we have to open the file for reading:
In [ 5 ]: f = open(‘./data/array.npy’, ‘r’)
This open file can now be written, choosing here binary transfer, by the STOR command in
combination with the target filename:
In [ 6 ]: ftp.storbinary(‘STOR array.npy’, f)
Out[6]: ‘226 Transfer complete.’
Let us have a look at the directory of the FTP server. Indeed, the file was transferred:
In [ 7 ]: ftp.retrlines(‘LIST’)
Out[7]: -rw––- 1 1001 1001 80080 Sep 29 11:05 array.npy
‘226 Directory send OK.’
The other way around is pretty similar. To retrieve a distant file and to save it to disk, we
need to open a new file, this time in write mode:
In [ 8 ]: f = open(‘./data/array_ftp.npy’, ‘wb’).write
Again, we choose binary transfer, and we use the RETR command for retrieving the file
from the FTP server:
In [ 9 ]: ftp.retrbinary(‘RETR array.npy’, f)
Out[9]: ‘226 Transfer complete.’
Since we do not need the file on the server anymore, we can delete it:
In [ 10 ]: ftp.delete(‘array.npy’)
Out[10]: ‘250 Delete operation successful.’
In [ 11 ]: ftp.retrlines(‘LIST’)
Out[11]: ‘226 Directory send OK.’