butterflyTee 0 Light Poster
import sys

def main():

usage = 'Usage: %s [options] <file name>\n' % sys.argv[0]
options =           'Options:\n'
options = options + '  -c, --chars    print the character counts\n'
options = options + '  -l, --lines    print the newline counts\n'
options = options + '  -w, --words    print the word counts\n'
usage = usage + options
 
countChars = 0
countWords = 0
countLines = 0

main()


and 


import sys

def main():

filename = "test.txt" 

try: 
    file = open(filename) 
except IOError, why: 
    print 'Unable to open file.\n', why 
    sys.exit(-1) 

charCount = lineCount = wordCount = 0 

for line in file.xreadlines(): 
    lineCount += 1 
    wordCount += len(line.split()) 
    charCount += len(line) 

print lineCount, wordCount, charCount

main()

Dani AI

Generated

Two clear, quick fixes explain why these scripts fail for many people.

First, the body of def main(): in both snippets is not indented, so Python will raise an IndentationError (or the function is effectively empty). Second, the examples use Python 2 idioms (old print form, exception syntax, and a file iterator method that is not present under Python 3). Running the code under the wrong Python interpreter produces SyntaxError or AttributeError; confirm which interpreter is in use with python --version.

A compact, modern approach (Python 3) fixes both problems: keep the function body indented, open files with a context manager, iterate the file to stream large files, and use current exception and print syntax.

def count_file(path):
    lines = words = chars = 0
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            lines += 1
            words += len(line.split())
            chars += len(line)
    return lines, words, chars

if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        print("usage: {} filename".format(sys.argv[0]))
        sys.exit(1)
    print(*count_file(sys.argv[1]))

Extra tips: use if __name__ == "__main__": to control execution; prefer argparse for option parsing; for very large files avoid reading the whole file into memory; if you need to run Python 2 code, launch it explicitly as python2 script.py. This addresses the most common runtime problems seen in 's examples.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.