如何计算行数(包括Python中的换行符)?

我一直在寻找一种计算行数的方法,该方法还包括结尾的新行。这样的方法不起作用:

ATTACH

文件的示例可以是def file_len(fname): with open(fname) as f: for i,l in enumerate(f): pass return i + 1

file.txt

由于我无法使代码格式正常工作(换行符),因此此处代表空行(因此,在前一行的末尾有换行符)。我希望行数为4,但是该函数的值为3。我应该怎么做才能完成这种行为?

zqplyn1234 回答:如何计算行数(包括Python中的换行符)?

在这种情况下,您需要对行进行计数(与对代码的处理一样),但是请检查最后一行是否以"\n"结尾,以及是否确实使计数器增加1。>

我也做了一些小的修改以摆脱i +1 然后我添加了两张用于调试的照片。

def file_len(fname):
    # comment or remove next two lines after debugging
    import os ; print("file has a size of %d bytes" % os.path.getsize(fname))
    print("file contents: %r" %  open(fname).read())
    with open(fname) as f:
        for i,l in enumerate(f,1):
            pass
            # comment or remove next line after debugging
            print("line is %r" % l)
    if i > 0 and l.endswith("\n"):  # increase line count if last line ends with "\n"
        i += 1
    return i

我的输出如下:

file has a size of 22 bytes
file contents: 'line 1\nline 2\nline 3\n\n'
line is 'line 1\n'
line is 'line 2\n'
line is 'line 3\n'
line is '\n'

我建议您复制粘贴我的确切代码并显示输出

本文链接:https://www.f2er.com/3108051.html

大家都在问