我的应用程序需要从远程 FTP 下载所有目录,我第一次测试 Python 的 ftplib。
当我尝试使用命令 ftp.nlst() 列出远程 FTP 中的所有目录时,它返回一个空列表。我确定该目录不为空,因为此命令:ftp.retrlines('list') 返回了一个显示目录内子文件夹名称的对象。
在测试时,我尝试了其他命令,例如 ftp.cwd('/other-dir/') 或 ftp.pwd(),但这些似乎都不是去工作。
这是我用来显示子目录列表的代码:
from ftplib import FTP
def ftpConnection():
ftp = FTP('ftp-address')
ftp.login('user', 'password')
lista = ftp.nlst()
return (lista)
print(ftpConnection())
输出:
[]
如您所见,列表是空的。
这是我的retrlines代码:
def ftpConnection():
ftp = FTP('remoteFtp')
ftp.login('user', 'password')
ftp.retrlines('LIST')
print (ftpConnection())
输出:
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
这是命令行 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.
请您参考如下方法:
所以你自己用 ftp 看到了它(从行为我假设它是 Windows ftp.exe)。
dir命令,使用LISTFTP命令,返回文件夹;ls命令,它使用NLSTFTP 命令,不返回文件夹。
这就是 您的 FTP 服务器的行为方式 – 它不返回 NLST 中的文件夹。
如果您需要从您的 FTP 服务器检索文件夹,您必须使用LIST:
