Next / Previous / Contents / TCC Help System / NM Tech homepage

4.8.  writeFile(): Assemble one output file

The input to this function is the name of an output file to be written (fileName), and a list of all the programlisting nodes (nodeList) containing code fragments destined for that output file. Its purpose is to extract all the text from each node and write it to the given file.


# - - -   w r i t e F i l e   - - -

def writeFile ( fileName, nodeList ):
    """Create a file from the text descendants of nodes in nodeList

      [ (fileName is a string) and
        (nodeList is a list of programlisting DOM Elements) ->
          if fileName is writeable ->
            file fileName  :=  text descendants of node in document order
          else ->
            sys.stderr  +:=  error message ]
    """
      

First, we try to create the file, reporting errors and returning if that fails.

    #-- 1 --
    # [ if fileName can be created new ->
    #     outFile  :=  fileName opened new
    #   else ->
    #     sys.stderr  +:=  error message
    #     return ]
    try:
        outFile  =  open ( fileName, 'w' )
    except IOError, detail:
        sys.stderr.write ( "*** Can't create file '%s': %s\n" %
            (fileName, detail) )
      

Next, we create an empty list that will contain strings extracted from nodeList.

    #-- 2 --
    contents  =  []
      

Then we pass each fragment's node to the findText() function, which extracts the text and CDATA elements from that node's descendants. The result of that function is a string, which is appended to contents.

    #-- 3 --
    # [ contents is a list ->
    #     contents  +:= all text descendants of nodes in nodeList in
    #                   document order ]
    for  node in nodeList:
        #-- 2 body --
        # [ node is a programlisting DOM element ->
        #     contents  +:=  all text descendants of node in
        #                    document order ]
        contents.append ( findText ( node ) )
      

Finally, we use Python's .writelines() function, which conveniently accepts a list of strings, to write all the strings in contents to the output file, and close it.

    #-- 4 --
    # [ outFile  +:=  contents, concatenated ]
    outFile.writelines ( contents )
    outFile.close()