Allow setting mode on opening of file

svn: r17519
This commit is contained in:
Michiel Nauta 2011-05-17 17:22:03 +00:00
parent 34e6755e8b
commit fd4b980c3e

View File

@ -319,16 +319,16 @@ class OpenFileOrStdout:
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
class OpenFileOrStdin: class OpenFileOrStdin:
"""Context manager to open a file or stdin for reading.""" """Context manager to open a file or stdin for reading."""
def __init__(self, filename): def __init__(self, filename, add_mode=''):
self.filename = filename self.filename = filename
self.mode = 'r%s' % add_mode
self.filehandle = None self.filehandle = None
def __enter__(self): def __enter__(self):
if self.filename == '-': if self.filename == '-':
# TODO how to add U to mode?
self.filehandle = sys.stdin self.filehandle = sys.stdin
else: else:
self.filehandle = open(self.filename, "rU") self.filehandle = open(self.filename, self.mode)
return self.filehandle return self.filehandle
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, traceback):