[Pythonmac-SIG] Re: Printing to a file

David Goodger dgoodger@bigfoot.com
Sun, 21 May 2000 12:57:37 -0400


> From: "Robin B. Lake" <rbl@hal.cwru.edu>
> Date: Saturday, May 20, 2000 12:46
> 
> I'm reading HTML pages off the Web and trying to file the contents
> of each page into a Mac file.  I create the new file with a name
> derived from a line found on each Web page (no problem).  I'm then
> setting stdout to that file and printing the downloaded page:

If you're deriving the name of the file from the web page contents, you
should be reading the contents first, and creating the output file after.

I assume you've got a line like "fpout = open(...)" here.

> sys.stdout = fpout
> <SNIP>
> this = urllib.urlopen('http://spamframjam/sub1/sub2/page',parameters)
> print this.read()
> 
> later, at the bottom of the inner loop, I do:
> 
> fpout.close()
> 
> Problems:  Sometimes I can create the 25 files created in the inner loop,
> sometimes it hangs.
> 
> What I'd LIKE to be able to do is either copy the "this" instance above
> into the file created and pointed to by fpout.  copyfile(this,fpout) does
> not work.  Doing it that way would not tie up stdout.

instead of the lines above, use:

    fpout = open(...)
    this = urllib.urlopen('http://spamframjam/sub1/sub2/page',parameters)
    contents = this.read()
    fpout.write(contents)
    fpout.close()

Of course, you could compress this considerably by leaving out some or all
of the intermediate variables:

    open(...).write(urllib.urlopen('http://spamframjam/sub1/sub2/page',
                                    parameters).read())

This relies on Python to close the file for you too.

-- 
David Goodger    dgoodger@bigfoot.com    Open-source projects:
 - The Go Tools Project: http://gotools.sourceforge.net
 (more to come!)