繁体   English   中英

使用python脚本从FTP位置下载目录/文件

[英]Download directory/files from FTP location using python script

下载无法在python中工作?

我编写了一个简单的python程序,以从FTP位置获取文件,但是当我执行它时,它会显示错误[Errno 13]权限被拒绝的消息。

我的代码如下。 知道为什么它不起作用吗?

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()

ftplib的文档说(强调我的):

FTP.retrbinary(command,callback [,maxblocksize [,rest]])

以二进制传输模式检索文件。 该命令应为适当的RETR命令:“ RETR文件名”。 对于每个接收到的数据将调用回调函数 ,并使用单个字符串参数指定该数据块。

因此,这里有2种可能的错误原因:

  • destinationlocalPath可能指向不存在的文件夹或不可写的文件夹或文件(顺便说一句,您将在每次迭代中重写相同的文件...)
  • 如果未在单个块中传输文件,则尝试打开每个块的目标文件而不关闭任何内容

不要这样做,而是继续做您在下一行写的内容,或者甚至更好地使用with:

   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)

这样一来,您就可以看到在哪里写东西...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM