使用ftplib.retrlines下载ftp中文本文件的前N行 [英] Download the first N rows of text file in ftp with ftplib.retrlines
问题描述
我需要从python访问ftp服务器,并下载特定文本文件的前N行.
I need to access an ftp server from python, and download the first N rows of a specific text file.
我了解了ftplib和函数目录,但是我不明白如何仅在不下载整个文件的情况下检索前N行(但是我想知道在ftp协议中是否可以做到这一点)
I read about ftplib and function retrlines, but I didn't understand how to retrieve the first N lines only without downloading the entire file (However I wonder whether that is possible in the ftp protocol)
推荐答案
您可以通过引发异常来中止文件下载.
You can abort the file download by throwing an exception.
尽管如此,您必须明确进行清理,否则将由retrlines
完成.
Though then you have to explicitly do a cleanup that would otherwise by done by the retrlines
.
c = 1
class TooManyLines(Exception):
pass
contents = ""
def collectLines(s):
global contents, c
contents += s + "\n"
c += 1
if c == 5:
raise TooManyLines()
try:
ftp.retrlines("RETR /path/file.txt", collectLines)
except TooManyLines:
# read/skip response
ftp.getmultiline()
清洁程序将复制retrlines
实现,并根据需要对其进行修改.
Cleaner would be to copy over retrlines
implementation and modify it as you need.
这篇关于使用ftplib.retrlines下载ftp中文本文件的前N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!