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) 
7
  • 4
    May be you have a newline at the end of the file? Commented Apr 5, 2014 at 12:50
  • Also, semi colons are so Cish... Commented Apr 5, 2014 at 12:50
  • And reading the entire file at a time is not very efficient. Commented Apr 5, 2014 at 12:51
  • 1
    what output do you get if you do Lines = allLines.splitlines() Commented Apr 5, 2014 at 12:51
  • 1
    First, if you check a script, they ALL have a last line (blank) for interpreters: it is the ctrl-z/d that you use from CLI. Second, use an incremental reader: you don't know how large the file is. I teach my lesson after I try to read an 8Gb iso with sh extension on my old pocket PC with 256 Mb RAM... Commented Apr 5, 2014 at 12:56

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Try this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.