Safely dealing with arbitrary file objects

Steven D'Aprano steve at
Sun Oct 14 06:01:53 CEST 2007

I have found myself writing functions rather like these:

def openfile(filename):
    if filename == '-':
        # convention for shell scripts in Unix-land is to use
        # '-' for stdin/stdout for reading/writing.
        outfile = sys.stdout
    if filename == '2-':
        outfile = sys.stderr
        outfile = file(filename, 'w')
    return outfile

def closefile(fileobj):
    # don't close standard file objects, or their replacements
    if not fileobj in (sys.stdout, sys.stderr, sys.stdin, 
    sys.__stdout__, sys.__stderr__, sys.__stdin__):

def processfile(filename):
    outfile = openfile(filename)
        # lots of processing here, which may raise exceptions
        var = "stuff happens"

A question:

I know I'm being paranoid about not closing files I shouldn't close, but 
am I being excessively paranoid, or not paranoid enough?

Suggestions for improvements welcome; while I'm happy to read suggestions 
using the new with statement, I can't yet rely on having Python 2.5 or 
better so I have to stick to try...finally.


More information about the Python-list mailing list