Next / Previous / Contents / Shipman's homepage

16. Puzzle.__readFile(): Partition the input file

kkck
# - - -   P u z z l e . _ _ r e a d F i l e

    def __readFile ( self, inFile ):
        '''Split the file into framework and word list portions.

          [ inFile is a readable file ->
              if inFile contains at least one blank line ->
                inFile  :=  inFile advanced to end of file
                return ((list of non-comment lines from inFile up
                to the first blank line), (list of lines after the
                first blank line))
              else -> raise SyntaxError ]
        '''

First read the entire puzzle file as a list of strings, with trailing whitespace (include newlines) removed. Then we find the first empty string in the list, and return the two pieces of the file separated by that empty string. It is an error if there is no empty line in the file.

kkck
        #-- 1 --
        # [ inFile  :=  inFile advanced to end of file
        #   lineList := lines from inFile as strings with
        #       trailing whitespace trimmed, ignoring lines
        #       that start with COMMENT_CHAR ]
        lineList = [ line.rstrip()
                     for line in inFile
                     if ( (len(line) == 0) or
                          (line[0] != COMMENT_CHAR) ) ]

        #-- 2 --
        # [ if lineList contains any empty strings ->
        #     terminus  :=  the index of the first such string
        #   else -> raise SyntaxError ]
        try:
            terminus = lineList.index('')
        except ValueError:
            raise SyntaxError ( "There must be a blank line between"
                                "frame and word list." )

        #-- 3 --
        return (lineList[:terminus], lineList[terminus+1:])