I need to access an ftp server from python, and download the first N rows of a specific text file.
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.
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()
Cleaner would be to copy over retrlines
implementation and modify it as you need.