且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

恢复下载文件ftp python3.*

更新时间:2022-05-24 22:35:28

retrbinary命令接受可选的rest参数,该参数应包含一个字符串,该字符串指示重新开始传输的字节偏移量. transfercmd文档中对此有更详细的描述 a>;一些文件传输命令支持此可选参数.

The retrbinary command accepts an optional rest argument which should contain a string indicating the byte offset at which to restart the transfer. This is described in more detail in the transfercmd documentation; several of the file-transfer commands support this optional argument.

此功能是可选的,因此服务器可能不支持它.您应该准备好处理错误返回,然后退回以获取整个文件(或中止).

This facility is optional, so the server might not support it; you should be prepared to handle an error return, and fall back to fetching the entire file (or aborting).

您的调用代码当然应该设置为追加到未完成的文件中,而不是覆盖它!

Your calling code should of course be set up to append to the unfinished file, rather than overwrite it!

未经测试,不在我的计算机上:

Untested, not at my computer:

import ftplib
import os

path = '/'
filename = '100KB.zip'
ftp = ftplib.FTP("speedtest.tele2.net") 
ftp.login("anonymous", "") 
ftp.cwd(path)
if os.path.exists(filename):
    restarg = {'rest': str(os.path.getsize(filename))}
else:
    restarg = {}
ftp.retrbinary("RETR " + filename ,open(filename, 'ab').write, **restarg)
print("untranslated string in some Slavic language?\n")
ftp.quit()

Python **kwargs表示法允许我们使用字典在函数调用中传递关键字参数.如果文件不存在,则传递一个空字典(不包含其他关键字参数),否则传递一个包含关键字'rest'及其值的dict.在这两种情况下,我们都使用文件模式'ab',它将附加到现有的二进制文件中,或者简单地创建一个新的二进制文件,然后打开以进行写入.

The Python **kwargs notation allows us to use a dictionary to pass keyword arguments in a function call. We pass an empty dictionary (no additional keyword arguments) if the file doesn't already exist, and otherwise a dict containing the keyword 'rest' and its value. In both cases we use a file mode 'ab' which will append to an existing binary file, or simply create a new binary file otherwise, and open it for writing.