Skip to content

Instantly share code, notes, and snippets.

@andrewsuzuki
Created May 6, 2014 18:49
Show Gist options
  • Save andrewsuzuki/d5f9d293020899f99ec5 to your computer and use it in GitHub Desktop.
Save andrewsuzuki/d5f9d293020899f99ec5 to your computer and use it in GitHub Desktop.
Counts lines, words, and characters of a file
#!/usr/bin/env python3.1
import os
def docount(string):
lines = string.split("\n")
line_count = len(lines)
word_count = 0
char_count = 0
for line in lines:
words = line.split()
word_count += len(words)
char_count += len(line)
return {
'l': line_count,
'w': word_count,
'c': char_count,
}
def countfile(thefile):
if os.path.isfile(thefile):
counts = docount(open(thefile).read())
print("File has {0} lines, {1} words, {2} characters".format(
counts['l'], counts['w'], counts['c']))
return True
else:
print("File does not exist, try again.")
return False
counted = False
while not counted:
if countfile(input('Which file would you like to count?')):
counted = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment