Week 7, Friday: File IO, Top-Down Design



implement readSystemWords(filename) function:

Given the name of the system word file, read in all words, store them in a list, and return the list to main(). Use the str method strip() to get rid or leading and trailing whitespace (spaces, tabs, newline characters).

def readSystemWords(filename):
  """open system file, read words into a list"""
  infile = open(filename, "r")
  words = []
  for line in infile:
     words.append(line.strip())
  infile.close()
  return words

Once you write a function, add some code to main() to test it and make sure it works! You could print the entire word list, but it has 99,000+ words, so that is a lot of output. Maybe just print len(words) and a few entries from the list?

implement the readFile(filename) function:

Given the name of the user file, read in all words, store them in a list, and return them to main(). Note: this is very similar to the first function we wrote. It is possible we could just use one function for both. Our design calls for two functions, but I often revise my design later if I see something like this.

For now, just write a second function to do this:

Note: use the str methods split() and strip() for this function. Here are some examples of how to use them:

>>> line = "Hey, how are you?"
>>> words = line.split()
>>> print words
['Hey,', 'how', 'are', 'you?']
>>> words[3].strip("?!.,")
'you'
>>> words[0].strip("?!.,")
'Hey'

See if you can get the readFile() function working with the gba.txt file. Can you get a clean list of words from gba.txt?