0

This is the code I use to count lines in a file. I don't think it is wrong. But why the result is always one line more than I check directly using gedit ? I can just minus 1 to get the right result but I want to know why.

        file = open(filename)
        allLines = file.read()
        file.close()
        Lines=allLines.split('\n')
        lineCount = len(Lines) 
hidemyname
  • 3,791
  • 7
  • 27
  • 41

2 Answers2

2

Here is the memory-efficient and pythonic way to iterate through the file and count its lines (separated with \n).

with open(filename) as file:
    lines_count = sum(1 for line in file)
Ivan Klass
  • 6,407
  • 3
  • 30
  • 28
0

Try this :

file_handle = open('filename.txt', 'r')
newlines=len(file_handle.readlines())
print('There are %d lines in the file.' % (newlines))
efdummy
  • 684
  • 1
  • 8
  • 9