尝试从FTP服务器下载.zip时获取TypeError

时间:2012-07-14 21:39:20

标签: python ftp download ftplib

我正在尝试从FTP服务器下载.zip文件,但我一直收到此错误:

File "C:/filename.py", line 37, in handleDownload
file.write(block)
TypeError: descriptor 'write' requires a 'file' object but received a 'str'

这是我的代码(借鉴http://postneo.com/stories/2003/01/01/beyondTheBasicPythonFtplibExample.html):

def handleDownload(block):
    file.write(block)
    print ".",

ftp = FTP('ftp.godaddy.com') # connect to host
ftp.login("auctions") # login to the auctions directory
print ftp.retrlines("LIST")
filename = 'auction_end_tomorrow.xml.zip'
file = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, handleDownload)
file.close()
ftp.close()

1 个答案:

答案 0 :(得分:2)

我自己无法重现这一点,但我知道发生了什么 - 我只是不确定 它是如何发生的。希望有人可以插入。注意file没有传递给handleDownload,file也是内置类型的名称。如果将file保留为内置,那么您将收到此错误:

>>> file
<type 'file'>
>>> file.write("3")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'write' requires a 'file' object but received a 'str'

所以我认为一些问题是file(内置)和file(打开的文件本身)之间的混淆。 (可能使用"file"以外的名称是一个好主意。)无论如何,如果你只是使用

ftp.retrbinary('RETR ' + filename, file.write)

并完全忽略handleDownload函数,它应该可以工作。或者,如果你想保持每个街区的点印刷,你可能会有点发烧友,并写下像

这样的东西
def handleDownloadMaker(openfile):
    def handleDownload(block):
        openfile.write(block)
        print ".",
    return handleDownload

这是返回指向正确文件的函数的函数。之后,

ftp.retrbinary('RETR' + filename, handleDownloadMaker(file))

也应该有用。