Question

I want to know the line numbers of a certain file Following is the code

But the result is not correct:The true file line number == Console result number + 1

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

if there are contents in the last line, the result is correct

import os
import os.path

absPath = os.curdir

while True:  
    print '\nplease select the file you want to know the 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 the fileName or the input is not a file'
Was it helpful?

Solution 2

I find the reason: the notepad++ line num(left side) shows 6, but open().readlines() return list ['aaa\n','bbb\n','ccc\n','\n','\n']

'\n' will add a new line num in editor,but not add a list num

So if the last line is like 'bbb',the script is correct if the last is like '\n' ,'\n',the line num must add 1

OTHER TIPS

You shouldn't use readlines() here, as it unnecessarily loads the whole file into memory. The following snippet is more memory-friendly:

with open(filename) as f:
    line_count = sum(1 for line in f)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top