[Tutor] Assigning a variable to an FTP directory listing

David bouncingcats at gmail.com
Thu Dec 12 01:24:48 CET 2013


On 12 December 2013 10:55, Pat Martin <wpmartin at gmail.com> wrote:
> Hello,
>
> I am writing a program that needs to pull all of the files from a
> specific directory. I have a few lines written that give me the list
> of files but when I try to assign it to a variable the variable ends
> up equaling "226 Directory send Ok", this is a snippet of my code.
>
> ftp=FTP(ftpserver)
> ftp.login(user=username,passwd=password)
> ftp.cwd(remoteworkdir)
> listoffiles = ftp.retrlines('NLST')
> print listoffiles
> ftp.quit()
>
> The output I get is:
>
> sampleone
> samplethree
> sampletwo
> 226 Directory send OK.
>
> The list of files I get is just from running the ftp.retrlines command
> it isn't because of the variable printing. If I do it without the
> assignment of the listoffiles variable it just lists the files from
> running that command and the Directory send OK isn't there.
>
> Any ideas on how I can assign just the list of files to a variable
> that I can do a for loop to go through and download?

The ftplib documentation says:

FTP.retrlines(command[, callback])

Retrieve a file or directory listing in ASCII transfer mode. command
should be an appropriate RETR command (see retrbinary()) or a command
such as LIST, NLST or MLSD (usually just the string 'LIST'). LIST
retrieves a list of files and information about those files. NLST
retrieves a list of file names. On some servers, MLSD retrieves a
machine readable list of files and information about those files. The
callback function is called for each line with a string argument
containing the line with the trailing CRLF stripped. The default
callback prints the line to sys.stdout.

The relevant sentence is "The default callback prints the line to sys.stdout.".

If you want to do more than simply "print the line to sys.stdout", you
have to provide your own my_callback_function (in your case it would
build a list) and specify it like this:

ftp.retrlines('NLST', my_callback_function)


More information about the Tutor mailing list