Method Name:
retrlines
Method Signature:
retrlines(command, callback=None);
Parameters:
command – An appropriate FTP command to retrieve a file or listing of the contents of a directory. The command should be compatible one for ASCII mode of transfer.
Callback – A callback function that is called for each line of ASCII text received from the server. The default value of this parameter is None.
Returns:
A success message 226 Transfer complete or a failure message like 550 Failed to open file.
Overview:
- The method retrlines()initiates a transfer of file or contents for the commands like RETR <filename.txt>, LIST.
- Before sending the RETR or LIST commands to the FTP server, the retrlines()internally sets the transfer mode as ASCII by sending the FTP command Type A to the server. To transfer binary files, the method retrbinary() shall be used.
Example – Preprocess each line of LIST command using retrlines() and print:
The example Python program sends a LIST command to the FTP server. Each line received from the FTP server is processed by a callback function and the function prepends each line with two asterisks and appends them with one asterisk.
# Example python program to list the contents of a directory # from an FTP server from ftplib import FTP
def listLineCallback(line): msg = "** %s*"%line; print(msg);
# Connect to the FTP server ftp = FTP(host="host2connectwith"); welcomeMessage = ftp.getwelcome(); print(welcomeMessage);
# Login respMessage = ftp.login(); print(respMessage);
# Get the current working directory respMessage = ftp.retrlines("LIST", listLineCallback); print(respMessage); |
Output:
220 (vsFTPd 3.0.3) 230 Login successful. ** -rw-r--r-- 1 0 0 1024 Feb 19 2016 1A.txt* ** -rw-r--r-- 1 0 0 1024 Feb 19 2016 2B.txt* ** -rw-r--r-- 1 0 0 1024 Feb 19 2016 3C.txt* ** -rw-r--r-- 1 0 0 1024 Feb 19 2016 4D.txt* ** -rw-r--r-- 1 0 0 1024 Feb 19 2016 5E.txt* ** -rw-r--r-- 1 0 0 1024 Feb 19 2016 6F.txt* ** -rw-r--r-- 1 0 0 1024 Feb 19 2016 7G.txt* ** drwxr-xr-x 2 105 108 4048 Oct 09 14:11 myuploads* 226 Directory send OK. |
Example - Using Python, transfer a text file from an FTP Server in ASCII mode:
# Example python program to retrieve a file in ASCII mode # from an FTP server from ftplib import FTP
def fileLineCallback(line): contentLine = "##%s#"%line; print(contentLine);
# Create an FTP instance ftpObject = FTP();
# Connect to the FTP server ftpObject.connect(host="host2connectwith"); respMessage = ftpObject.getwelcome(); print(respMessage);
# Login respMessage = ftpObject.login(); print(respMessage);
# Get a file in ASCII mode respMessage = ftpObject.retrlines("RETR SampleFile.txt", fileLineCallback); print(respMessage); |
Output:
220 (vsFTPd 3.0.3) 230 Login successful. ##One# ##Two# ##Three# ##Four# ##Five# 226 Transfer complete. |