Why the result is not correct using python to know the line numbers of a file -


i want know line numbers of file following code

but result not correct:the true file line number == console result number + 1

is problem in "open().readlines()" ?

if there contents in last line, result correct

import os import os.path  abspath = os.curdir  while true:       print '\nplease select file want know line nums:'     print os.listdir(abspath)          filename = raw_input()      absfilepath = abspath + '//' + filename     if os.path.isfile(absfilepath):         count = len(open(absfilepath).readlines())         print 'the ' + filename + ' file line nums is>>>' + str(count) + '>>>'     else:         print 'please check filename or input not file' 

you shouldn't use readlines() here, unnecessarily loads whole file memory. following snippet more memory-friendly:

with open(filename) f:     line_count = sum(1 line in f) 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -