2

我正在尝试从 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()
4

1 回答 1

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

也应该工作。

于 2012-07-14T22:08:47.030 回答