How to count lines in a text file ?

Phil Frost indigo at bitglue.com
Mon Sep 20 09:27:48 EDT 2004


Yes, you need a for loop, and a count variable. You can count in several
ways. File objects are iterable, and they iterate over the lines in the
file. readlines() returns a list of the lines, which will have the same
effect, but because it builds the entire list in memory first, it uses
more memory. Example:

########

filename = raw_input('file? ')
file = open(filename)

lines = 0
for line in file:
  # line is ignored here, but it contains each line of the file,
  # including the newline
  lines += 1

print '%r has %r lines' % (filename, lines)

########

another alternative is to use the standard posix program "wc" with the
-l option, but this isn't Python.

On Mon, Sep 20, 2004 at 03:18:53PM +0200, Ling Lee wrote:
> Hi all.
> 
> I'm trying to write a program that:
> 1) Ask me what file I want to count number of lines in, and then counts the 
> lines and writes the answear out.
> 
> 2) I made the first part like this:
> 
> in_file = raw_input("What is the name of the file you want to open: ")
> in_file = open("test.txt","r")
> text = in_file.read()
> 
> 3) I think that I have to use a for loop ( something like: for line in text: 
> count +=1)
> Or maybee I have to do create a def: something like: ( def loop(line, 
> count)), but not sure how to do this properly.
> And then perhaps use the readlines() function, but again not quite sure how 
> to do this. So do one of you have a good idea.
> 
> Thanks for all help



More information about the Python-list mailing list