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

2

13

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 ?

Dilatory answered 6/9, 2015 at 5:20 Comment(0)
B
13

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.

Brechtel answered 7/9, 2015 at 6:38 Comment(0)
J
10

You can use FTP.nlst() method. It returns the file names as a list.

>>> FTP.nlst('path')
['x','y','z']
Jurat answered 14/2, 2017 at 17:35 Comment(2)
This does not work in python 3.8Tacky
It does work. Could it be that your FTP server does not support it? docs.python.org/3.10/library/ftplib.html#ftplib.FTP.nlstCredent

© 2022 - 2024 — McMap. All rights reserved.