CS 204: Software Design

Due 8:30AM Wednesday, 13 January 2010. Hand in both programs via your Courses hand-in folder.

A Python warm-up

Your job for this assignment is to write the following pair of Python programs.

  1. Call the first program renamefiles.py. When executed like this:

    python renamefiles.py sourcedir destinationdir

    your program should traverse the specified source directory, and copy each of the non-directory files (also known as "regular files") it encounters into the destination directory.

    When the program copies a file, the copy should be named by concatenating the names of the directories in the path of the file, separated by underscores, followed by the file's original name. For example, suppose sourcedir is Photos, and the Photos directory contains a subdirectory named 2009, which in turn contains a file named Kudu.jpg (from the photos you took on your safari, naturally). Then the name of the copy of Kudu.jpg should be Photos_2009_Kudu.jpg.

  2. Call the second program gettitle.py. When executed like so:

    python gettitle.py webaddress

    this program should retrieve the text of the specified web page, extract from it the contents of the page's <title> tag, strip the white space off either end of the title, and print the stripped title to standard output.

    For this program, I would recommend that you define a couple utility functions to help you solve the overall problem. If I were writing this program, I would first write and test a function like this:

    def getPageText(address): '''Retrieves the web page with the specified address, and returns a string containing the full text of the page.'''

    This just encapsulates a few lines of slightly ugly code into an easily used function.

    Second, I would write and test a function like this:

    def getTagBody(text, tagName): '''Finds the first opening and closing tag pair of the specified tag name in the specified text, and returns the body of that tag. For example, if text is "A <b>big</b> elk" and tagName is "b", then getTagBody will return "big".'''

    You may organize your code differently if you prefer. But a couple well-focused functions like this can make the overall task easy to perform, and the resulting code easy to understand.

A little help

You may find the following sample programs useful as you work on these problems.