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'
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