file open/close functions can process any stream *filename*

This commit is contained in:
Oliver Beckstein
2014-06-09 11:58:13 -07:00
parent 2b6c20e9a6
commit f17fc9acfe

View File

@@ -9,18 +9,49 @@ import pkg_resources
# file I/O # file I/O
# #
def open_file_for_reading(filename): def open_file_for_reading(filename):
"""Open file or file-like stream *filename* for reading.
*filename* may be a string and then it is opened but if it is a
file-like object (such as an open :class:`file` or
:class:`StringIO.StringIO` --- really anything with ``next()``,
``read()``, ``readlines()``, ``readline``, ``close`` methods) then
the object is just passed through (the stream is attempted to be
reset to the beginning with ``fseek(0)``).
"""
if hasattr(filename, 'next') and hasattr(filename, 'read') \
and hasattr(filename, 'readline') and hasattr(filename, 'readlines') \
and hasattr(filename, 'close'):
# already a stream
try:
filename.fseek(0)
except AttributeError:
pass
return filename
try: try:
f = open(filename,'r') f = open(filename,'r')
except: except:
raise Exception('Cannot find file %s' %filename) raise IOError('Cannot find file %s' %filename)
return f return f
def open_file_for_writing(filename): def open_file_for_writing(filename):
"""Open file or file-like stream for writing"""
if hasattr(filename, 'write') and hasattr(filename, 'writeline') and hasattr(filename, 'writelines') \
and hasattr(filename, 'close'):
# already a stream
try:
mode = filename.mode
except AttributeError:
mode = "w"
if not ("w" in mode or "a" in mode or "+" in mode):
raise IOError("File/stream not open for writing")
return filename
try: try:
res = open(filename,'w') f = open(filename,'w')
except: except:
raise Exception('Could not open %s'%filename) raise Exception('Could not open %s'%filename)
return res return f
# #
# bookkeeping etc. # bookkeeping etc.
@@ -193,10 +224,10 @@ def writeFile(filename, lines):
""" """
Writes a new file Writes a new file
""" """
file = open(filename, 'w') f = open_file_for_writing(filename)
for line in lines: for line in lines:
file.write( "%s\n" % (line) ) f.write( "%s\n" % (line) )
file.close() f.close()