hidemyname
hidemyname

Reputation: 4287

How to count the precise line number in a file with python?

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) 

Upvotes: 0

Views: 92

Answers (2)

efdummy
efdummy

Reputation: 704

Try this :

file_handle = open('filename.txt', 'r')
newlines=len(file_handle.readlines())
print('There are %d lines in the file.' % (newlines))

Upvotes: 0

Ivan Klass
Ivan Klass

Reputation: 6627

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)

Upvotes: 2

Related Questions