2016-07-05 197 views
0

下载不能在python中工作?使用python脚本从FTP位置下载目录/文件

我写了一个简单的python程序,为了从FTP位置获取文件,但是当我执行它时,它给出了错误[Errno 13] Permission denied message。

我的代码如下。任何想法为什么它不工作?

import ftplib 
from ftplib import FTP, error_perm 

def getFTPDir(dirpath): 

    f = ftplib.FTP(ip, username, password) 

    try: 
     f.cwd(dirpath) 
     nameList = f.nlst() 
     oldest = nameList[0] 
     newest = nameList[-1] 

     newest = oldest 

     newDirPath = dirpath +'/'+ newest 

     print f.cwd(newDirPath) 
     subNameList = f.nlst() 

     for i in range (len(subNameList)): 
      f.cwd(newDirPath + '/' + str(subNameList[i])) 
      nameList1 = f.nlst() 

      filename = nameList1[i] 
      print "downloading..............", filename 


      f.retrbinary('RETR '+ filename, open(os.path.join(destination,localPath),"wb").write) 
      print filename + " downloaded" 

      try: 
       fhandle = open(filename, 'wb') 
       f.retrbinary('RETR ' + filename, fhandle.write) 

      except Exception, e: 
       print str(e) 

      finally: 
       fhandle.close() 

    except error_perm: 
     return 

    except Exception, e: 
     print str(e) 

    finally: 
     f.close() 
+0

请在哪一行出现错误说...' –

+0

f.retrbinary('RETR'+ filename,open – Dush

回答

0

FTPLIB的文档说(强调矿):

FTP.retrbinary(命令,回调[,maxblocksize [,休息]])

检索二进制传输模式文件。命令应该是一个合适的RETR命令:'RETR filename'。 为每个接收到的数据块调用回调函数,使用一个字符串参数给出数据块。

因此,有2个可能的错误会导致在此:

  • destinationlocalPath可以指向一个不存在的文件夹或不写文件夹或文件(顺便说一句,你将改写在每次迭代相同的文件...)
  • 如果在一个单块未转移的文件,试图打开每个块的目标文件,但不关闭任何

这样不行,b UT继续做你的下一行写的,甚至更好的使用有:

try: 
     localname = os.path.join(destination,localPath) 
     # a spy to control the names, comment it out when it works 
     print filename, " -> ", localname 
     with open(localname, 'wb') as fhandle 
      f.retrbinary('RETR ' + filename, fhandle.write) 

    except Exception as e: 
     print str(e) 

这样的话,你可以看到你尝试写...