Python - 通过 ftp 获取文件的行数

Python - get line count of a file via ftp

我正在尝试使用 ftplib 来计算文件中的行数。到目前为止,这是我想出的。

ftp = FTP('ftp2.xxx.yyy')
ftp.login(user='xxx', passwd='yyy')
count = 0
def countLines(s):
    nonlocal count
    count += 1
    x=str(s).split('\r')
    count += len(x)

ftp.retrbinary('RETR file_name'], countLines)

但是行数少了一些(我多了 20 行),我该如何解决/有没有更好更简单的解决方案

你必须使用 FTP.retrlines,而不是 FTP.retrbinary

count = 0
def countLines(s):
    global count
    count += 1

ftp.retrlines('RETR file_name', countLines)

对于FTP.retrbinary

The callback function is called for each block of data received

同时 FTP.retrlines:

The callback function is called for each line with a string argument containing the line with the trailing CRLF stripped.


使用 FTP.retrbinary 你会得到更多,因为如果一个块在一行的中间结束,那么该行被计算两次。

按照建议,使用FTP.retrlines,但如果你必须使用FTP.retrbinary,你将需要指望每个“\n”,并且也不是每个回调。

import ftplib

class FTPLineCounter(object):

    def __init__(self):
        self.count = 0

    def __call__(self, file_text):
        """Count the lines as the file is received"""
        self.count += file_text.count(b"\n")



ftp = ftplib.FTP("localhost")
ftp.login()

counter = FTPLineCounter()

ftp.retrbinary("RETR file_name", counter)

print(counter.count)