Tuesday, April 10, 2007

Counting number of lines in a file @ python

f = open(filename)
lines = f.readlines()
f.close()

print "%s has %d lines." % (filename, len(lines))

1 comment:

dnunes said...

. . The problem with this approach is that you need to load the *whole* file into memory (as a list) to count its lenths. A better approach would be something like...

f=open(r'file.txt', 'r');
lines=sum(1 for line in f)