[Courses] [python] Lesson 4: Modules and command-line arguments

lenore borisova orangegirl at gmail.com
Mon Jul 11 07:02:07 UTC 2011


Below are my answers for Lesson 4. I am submitting them a bit later as I am
currently traveling.



1.  Running it without giving it an argument gives you an error of
"IndexError: list index out of range" because the list is too short. To
check to see if a user forgot to supply an argument, this works:


#! /usr/bin/env python


import sys


if len(sys.argv) >= 2:

        num = int(sys.argv[1])

        for arg in sys.argv[1:]:

                print arg

else:

        print "Error: An argument was not specified."



2.


#!` /usr/bin/env python


# program take filename, prints line nums in file


filename="test5.py"

file = open(filename)

for line in file:

        total = sum(1 for line in open(filename))

file.close()


print total



3. Counting lines in multiple files:


#! /usr/bin/env python


import sys


if len(sys.argv) >= 2:

        # num = int(sys.argv[1])

        for arg in sys.argv[1:]:

                file = open(arg)

                for line in file:

                        total = sum(1 for line in open(arg))

                file.close()

                print total

else:

        print "Error: An argument was not specified."


4.


a) word count and using split() and len()


#! /usr/bin/env python


import sys


if len(sys.argv) >= 2:

        for arg in sys.argv[1:]:

                file = open(arg)

                for line in file:

                        words = line.split(None)

                        print words

                        print len(words)

                file.close()

else:

        print "Error: An argument was not specified."



b) Yes, the word count was the same


c) Uhoh. The number of words in my program matched with wc -w. I tried
created different test files, and it consistently matched. I'm not sure what
to debug at this point.


More information about the Courses mailing list