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

これを自分で再現することはできませんが、何が起こっているのかはわかります。どのように起こっているのかわかりません。願わくば、誰かが参加してくれることを願っています。handleDownload にfileは渡されず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 に答える