Ad

Python Ftp.nlst() Return Empty List When Where Are (sub)directories On The Server

- 1 answer

My application needs to download all the directories from a remote FTP, I'm testing for the first time the Python's ftplib.

When I try to list all the directories in the remote FTP with the command ftp.nlst() it return an empty list. I know for sure that the directory is not empty because this command: ftp.retrlines('list') returned an object displaying the names of the subfolders inside the directory.

While I was testing I tried other commands like ftp.cwd('/other-dir/') or ftp.pwd(), but none of these seems to work.

This is the code that I'm using to display the list of subdirectories:

from ftplib import FTP

def ftpConnection():
    ftp = FTP('ftp-address')
    ftp.login('user', 'password') 
    lista = ftp.nlst()
    return (lista)

print(ftpConnection())

Output:

[]

As you can see the list is empty.


This is my code for retrlines:

def ftpConnection():
    ftp = FTP('remoteFtp')
    ftp.login('user', 'password') 
    ftp.retrlines('LIST')

print (ftpConnection())

Output:

drw-rw-rwx 1          512 Jun 29 09:23 .
drw-rw-rwx 1          512 Jun 28 05:11 103367
drw-rw-rwx 1          512 Jun 29 02:01 121901
drw-rw-rwx 1          512 Sep 23  2016 123233
drw-rw-rwx 1          512 Jun 29 09:19 125183
drw-rw-rwx 1          512 Jun 29 02:34 133028

This is the output from command-line ftp:

230-Welcome clt_kantar_italy from remoteFtp. You are now logged in to the server.
230 User logged in, proceed.
ftp> dir
200 PORT command successful.
150 File status okay; about to open data connection.
drw-rw-rwx 1          512 Jun 29 09:23 .
drw-rw-rwx 1         512 Jun 28 05:11 103367
drw-rw-rwx 1          512 Jun 29 02:01 121901
drw-rw-rwx 1          512 Sep 23  2016 123233
drw-rw-rwx 1          512 Jun 29 09:19 125183
drw-rw-rwx 1          512 Jun 29 02:34 133028
226 Closing data connection. Transferred 481 bytes.
ftp: 484 bytes received in 0.01secondi 37.23Kbyte/sec)
ftp> ls
200 PORT command successful.
150 File status okay; about to open data connection.
226 Closing data connection. Transferred 0 bytes.
Ad

Answer

So you see it yourself with ftp (from the behavior I assume it's Windows ftp.exe).

  • dir command, which uses LIST FTP command, returns the folders;
  • ls command, which uses NLST FTP command, does not return the folders.

So it's how your FTP server behaves – It does not return folders in NLST.

If you need to retrieve folders from your FTP server, you have to use LIST:

Ad
source: stackoverflow.com
Ad