1

Possible Duplicate:
How to get line count cheaply in Python?

I'd like to print how many lines there is in a file.

What I have so far is this, but it prints the number of every line and I'm not sure how to get Python to only print the last one.

filename = input('Filename: ')

f= open(filename,'r') 

counter = 1 

line = f.readline() 
while(line): 
    clean_line = line.strip() 
    print(counter) 
    line = f.readline()
    counter += 1
f.close()
Community
  • 1
  • 1
Nikolai Stiksrud
  • 157
  • 2
  • 4
  • 7

3 Answers3

3

I'd go for...

with open('yourfile') as fin:
    print sum(1 for line in fin)

This saves reading the file into memory to take its length.

Jon Clements
  • 132,101
  • 31
  • 237
  • 267
1
f = open(filename, 'r')
lines = f.readlines()
number_of_lines = len(lines)
f.close()
Steve Mayne
  • 21,307
  • 4
  • 47
  • 48
1

If you don't need to loop on each line, you could just use:

counter = len(f.readlines())
Nicolas
  • 5,265
  • 1
  • 23
  • 37