在这种情况下,您需要对行进行计数(与对代码的处理一样),但是请检查最后一行是否以"\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