使用 ftplib 下载部分文件
Downloading partial file with ftplib
有没有办法从最后一行(文件末尾)只下载部分文件。就像文件超过 40 MB,我只想检索最后一个块,比方说 2042 字节。有没有可能使用 python 3 和 ftplib 来做到这一点?
只需使用 retrbinary
的 rest
参数来告诉服务器它应该从哪个文件偏移量开始传输数据。来自 documentation:
FTP.retrbinary(command, callback[, maxblocksize[, rest]])
... rest means the same thing as in the transfercmd() method.
FTP.transfercmd(cmd[, rest])
... If optional rest is given, a REST command is sent to the server, passing rest as an argument. rest is usually a byte offset into the requested file, telling the server to restart sending the file’s bytes at the requested offset, skipping over the initial bytes.
尝试使用 FTP.retrbinary()
方法并提供 rest
参数,它是所请求文件的偏移量。由于偏移量是从文件的开头开始的,因此您需要使用文件的大小和所需的数据字节数来计算偏移量。这是使用 debian 的 FTP 服务器的示例:
from ftplib import FTP
hostname = 'ftp.debian.org'
filename = 'README'
num_bytes = 500 # how many bytes to retrieve from end of file
ftp = FTP(hostname)
ftp.login()
ftp.cwd('debian')
cmd = 'RETR {}'.format(filename)
offset = max(ftp.size(filename) - num_bytes, 0)
ftp.retrbinary(cmd, open(filename, 'wb').write, rest=offset)
ftp.quit()
这将从所请求文件的末尾检索最后 num_bytes
个字节,并将其写入当前目录中的同名文件。
retrbinary()
的第二个参数是回调函数,在本例中是可写文件的write()
方法。您可以编写自己的回调来处理检索到的数据。
有没有办法从最后一行(文件末尾)只下载部分文件。就像文件超过 40 MB,我只想检索最后一个块,比方说 2042 字节。有没有可能使用 python 3 和 ftplib 来做到这一点?
只需使用 retrbinary
的 rest
参数来告诉服务器它应该从哪个文件偏移量开始传输数据。来自 documentation:
FTP.retrbinary(command, callback[, maxblocksize[, rest]])
... rest means the same thing as in the transfercmd() method.FTP.transfercmd(cmd[, rest])
... If optional rest is given, a REST command is sent to the server, passing rest as an argument. rest is usually a byte offset into the requested file, telling the server to restart sending the file’s bytes at the requested offset, skipping over the initial bytes.
尝试使用 FTP.retrbinary()
方法并提供 rest
参数,它是所请求文件的偏移量。由于偏移量是从文件的开头开始的,因此您需要使用文件的大小和所需的数据字节数来计算偏移量。这是使用 debian 的 FTP 服务器的示例:
from ftplib import FTP
hostname = 'ftp.debian.org'
filename = 'README'
num_bytes = 500 # how many bytes to retrieve from end of file
ftp = FTP(hostname)
ftp.login()
ftp.cwd('debian')
cmd = 'RETR {}'.format(filename)
offset = max(ftp.size(filename) - num_bytes, 0)
ftp.retrbinary(cmd, open(filename, 'wb').write, rest=offset)
ftp.quit()
这将从所请求文件的末尾检索最后 num_bytes
个字节,并将其写入当前目录中的同名文件。
retrbinary()
的第二个参数是回调函数,在本例中是可写文件的write()
方法。您可以编写自己的回调来处理检索到的数据。