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
  • 138,671
  • 33
  • 247
  • 280
1
f = open(filename, 'r')
lines = f.readlines()
number_of_lines = len(lines)
f.close()
Steve Mayne
  • 22,285
  • 4
  • 49
  • 49
1

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

counter = len(f.readlines())
Nicolas
  • 5,583
  • 1
  • 25
  • 37