Python Count Lines and words

Python count lines in file:

[py collapse=”False”]
filename = raw_input(‘file? ‘)
file = open(filename)

lines = 0
for line in file:
lines += 1

print ‘%r has %r lines’ % (filename, lines)
[/py]

Python count words in file:

[py collapse=”False”]
filename = "words.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, ‘r’) as f:
for line in f:
words = line.split()

num_lines += 1
num_words += len(words)
num_chars += len(line)

print num_words
[/py]

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>