繁体   English   中英

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

为每个接收的数据块调用callback函数

而对于FTP.retrlines

使用字符串参数为每一调用callback函数,该字符串参数包含剥离尾部CRLF的行。


使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM