在我们进行文件下载之前,我们可能需要查看可供下载的文件列表,以列出Linux内核FTP网站(ftp.kernel.org)中的文件为例。
如果处理需要账户的FTP网站,需要提供用户名和密码。但Linux内核FTP网站不需要Linux内核FTP网站的用户名和密码,因为可以匿名登录。
要从选中的FTP网站中获取文件,可以使用ftplib库。
import ftplib
def test_ftp_connection(path, username, email):
#Open ftp connection
ftp = ftplib.FTP(path, username, email)
#List the files in the /pub directory
ftp.cwd("/pub")
print("File list at {}:".format(path))
files = ftp.dir()
print files
ftp.quit()
if __name__ == '__main__':
test_ftp_connection(path=FTP_SERVER_URL, username='anonymous', email='nobody@nourl.com')