Python ftplib: How to store results of `FTP.retrlines` in a list?

Tao Xiao picture Tao Xiao · Sep 6, 2015 · Viewed 7.7k times · Source

I'd like to retrieve files' name of a directory and I use the method ftplib.retrlines('NLST' + path).

It prints all files' names in the directory path. But I want to store those files' names in a container, e.g., a list, instead of printing them in the console. How to do that ?

Answer

Martin Prikryl picture Martin Prikryl · Sep 7, 2015

The second (optional) argument to the FTP.retrlines is a callback.

FTP.retrlines(command[, callback])

You can use it like:

lines = []
sess.retrlines('NLST ' + path, lines.append)

See also Creating list from retrlines in Python.