2012-12-10 53 views
1

我走過這似乎與已張貼了不少問題了,但是,我有不盡相同的問題下載二進制格式的壓縮文件:使用Python的FTPLIB

我使用python的FTPLIB模塊以及zipfile從二進制格式的ftp下載zip文件。但是,出於某種原因,下載的zip文件似乎是ascii。

我確保在我下載的文件的路徑中不存在領先的/(與zip規範相匹配)。

outFile = zipfile.ZipFile(local_file_path, 'w') 
myftp.retrbinary('RETR %s' %i, outFile.write(i)) #i - target file path on ftp server 

此代碼失敗給了我以下錯誤:

st = os.stat(filename) 
OSError: [Errno 2] No such file or directory: //$i 

我嘗試添加二進制的 'B' 的選項,但zip文件似乎不喜歡它:

outFile = zipfile.ZipFile(local_file_path, 'wb') 

這會產生錯誤:

RuntimeError: ZipFile() requires mode "r", "w", or "a" 

我正在使用python v2.6。

我在做什麼錯誤,以及如何解決它?

回答

0

據蟒蛇DOC(http://docs.python.org/2/library/ftplib.html)似乎retrbinary需要一個回調的第二個參數:

>>> ftp.retrbinary('RETR README', open('README', 'wb').write) 
'226 Transfer complete.' 
>>> ftp.quit() 

文件說:

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

Retrieve a file in binary transfer mode. command should be an appropriate RETR command: 'RETR filename'. The callback function is called for each block of data received, with a single string argument giving the data block. [...]

在你的榜樣應該outfile.write(而不是outfile.write(i))。

>>> ftp.retrbinary('RETR %s' % i, outFile.write)