Closing a file

David Bolen db3l at fitlinxx.com
Fri Jul 21 18:53:27 EDT 2000


"Duncan Smith" <buzzard at urubu.freeserve.co.uk> writes:

> The following seems to do exactly what I want.  It was suggested by a
> computer scientist who knows no Python (but I presume C).  Is 'sys.stdout =
> 0' a safe way of handling this?

Not if you want sys.stdout to continue functioning the way it normally
does (e.g., this might generate errors in other code that uses 'print') :-)

But yes, assigning sys.stdout to _anything_ else will remove the
reference to your open file (which sys.stdout is holding, but loses
when you point sys.stdout to reference something else - the integer 0
in this case) and the file object will then get closed and deleted.
That's basically the same suggestion that the first responder to your
original note mentioned.

If I might suggest, it would be cleaner to save the old contents of
sys.stdout when your function first reroutes it (just save it off in
self.old_stdout or whatever), and then restore to that value when
done.

You also mentioned along the thread that this was one of your first
programs.  I'm not sure if rerouting sys.stdout and then using 'print'
is a requirement of your application or if it's just the first way you
tried to get file output.

If you really just want to control output to the file, you could
ignore sys.stdout altogether, just keep your file reference in an
instance variable (say self.outputfile.write()) and then use normal
file routines to do your output.  Now in some cases they will differ a
bit because 'print' assumes it should convert everything to a string
before printing.  If you want that format in the file with a direct
write() you can convert the value into a string before calling write()
in various ways (calling str(), using "%s" % value, etc..)

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list