我正在尝试使用 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
,您可以获得更多,因为如果一个 block 在一行中间结束,则该行会被计算两次。
关于Python-通过ftp获取文件的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46446813/