Download the first N rows of text file in ftp with

2019-06-03 08:58发布

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)

1条回答
Melony?
2楼-- · 2019-06-03 09:24

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.

查看更多
登录 后发表回答