簡體   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