2013-01-24 46 views
0

快速簡單:使用python從FTP下載特定文件

我有以下功能,如果指定文件名,效果很好。

import os 
import ftplib 

def ftpcon(self, host, port, login, pwd, path): 

    ftp = ftplib.FTP() 
    ftp.connect(host, port, 20) 
    try: 

     ftp.login(login, pwd) 
     ftp.cwd(path) 

     for files in ftp.nlst(): 

      if files.endswith('.doc') or files.endswith('.DOC'): 

       ftp.retrbinary('RETR ' + files, open(file, 'wb').write) 
       print files 

但是當我使用for循環與ftp.nlst()來嘗試匹配特定類型的文件,我收到錯誤:

coercing to Unicode: need string or buffer, type found

因爲即時通訊不知道這是最好的方式來做到這一點,有什麼可以「正確」的方式來下載文件?

回答

0

也許嘗試:

from ftplib import FTP 

server = FTP("ip/serveradress") 
server.login("user", "password") 

server.retrlines("LIST") # Will show a FTP content list. 
server.cwd("Name_Of_Folder_in_FTP_to_browse_to") # browse to folder containing your file for DL 

則:

server.sendcmd("TYPE i") # ready for file transfer 
server.retrbinary("RETR %s"%("FILENAME+EXT to DL"), open("DESTINATIONPATH+EXT", "wb").write) # this will transfer the selected file...to selected path/file 

相信這是爲正確服務..

ü可以設置server.set_debuglevel(0)(1)或(2)登錄服務器時進行更詳細的描述。