【发布时间】:2012-07-19 09:41:15
【问题描述】:
我有以下代码可以轻松连接到 FTP 服务器并打开一个 zip 文件。我想将该文件下载到本地系统中。该怎么做?
# Open the file for writing in binary mode
print 'Opening local file ' + filename
file = open(filename, 'wb')
# Download the file a chunk at a time
# Each chunk is sent to handleDownload
# We append the chunk to the file and then print a '.' for progress
# RETR is an FTP command
print 'Getting ' + filename
ftp.retrbinary('RETR ' + filename, handleDownload)
# Clean up time
print 'Closing file ' + filename
file.close()
【问题讨论】:
-
我建议在这里使用
with,它负责在完成后关闭文件句柄:with open(filename, "wb") as file: ftp.retrbinary("RETR " + filename, file.write) -
FD 泄露可不是开玩笑的!当您使用它时,您可以将
file重命名为f,因为file会影响内置的file。 -
如果文件是文本文件,则使用
retrlines。