如何从3ftp站点下载文件

时间:2015-03-12 10:19:04

标签: python

我在文本文件中有一个ftp站点列表(例如:10),我需要从ftp站点下载最后创建的文件。这可能吗。这是我的代码:

import os
from ftplib import FTP

ftp = FTP("xxx.xx.xx.xx1", "USERNAME1", "PASSWORD1")
ftp = FTP("xxx.xx.xx.xx2", "USERNAME2", "PASSWORD2")
ftp = FTP("xxx.xx.xx.xx3", "USERNAME3", "PASSWORD3")
ftp = FTP("xxx.xx.xx.xx4", "USERNAME4", "PASSWORD4")
ftp = FTP("xxx.xx.xx.xx5", "USERNAME5", "PASSWORD5")

ftp.login()
ftp.retrlines("LIST")

ftp.cwd("SmythIN/2014-10-29") --- here  i have a folder created by current  date ...how can i pass current date folder i change directory.
ftp.cwd("subFolder") # or ftp.cwd("folderOne/subFolder")

listing = []
ftp.retrlines("LIST", listing.append)
words = listing[0].split(None, 8)
filename = words[-1].lstrip()

# download the file
local_filename = os.path.join(r"c:\myfolder", filename)
lf = open(local_filename, "wb")
ftp.retrbinary("RETR " + filename, lf.write, 8*1024)
lf.close() 

更新代码:

ftp.cwd("SmythIN/2014-10-29")- the directory with today date is already created.

1 个答案:

答案 0 :(得分:1)

只需循环遍历服务器并拉出指定目录中的最后一个文件(如果我理解你的问题)是直截了当的。记住每个文件来自哪个服务器应该没有问题,因为您可以在本地计算机上使用不同的本地目录或在文件传输时编辑文件名。以下是我的建议(当然要修改为您的应用程序):

import os
from ftplib import FTP

# read in text file containing server login information and jam into dictionary
with open('server_file.txt','r') as tmp:
    servers = {}
    for r in tmp.read().split('\n'):
        rs = r.split(',') # split r by comma
        servers[rs[0]] = {'uname':rs[1],'pwd':[rs[2]]}

# if you want to create a new directory to save the file to
heute = dt.datetime.strftime(dt.datetime.today(),'%Y%m%d')
if os.path.isdir('my_dir' + heute)==False:
    os.mkdir('my_dir' + heute)


for s in servers:
    ftp = FTP(s,servers[s]['uname'],servers[s]['pwd'])
    ftp.cwd('desired_subdir')

    # if you want to download the last file I would us nlst
    with open('local_file','wb') as lf:
        ftp.retrbinary('RETR' + ftp.nlst()[-1], lf.write, 8*1024)