Python Count Lines and words

Posted by on Apr 18, 2012 in python | No Comments

Python count lines in file:

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

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

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

Python count words in file:

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

Email this to someoneTweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponShare on RedditDigg this

Leave a Reply