@@ -91,84 +91,11 @@ def __init__(self, fileobj=None, mode='readonly', memmap=False):
9191
9292 # Initialize the internal self.__file object
9393 if isfile (fileobj ) or isinstance (fileobj , gzip .GzipFile ):
94- closed = fileobj_closed (fileobj )
95- fmode = fileobj_mode (fileobj ) or PYTHON_MODES [mode ]
96-
97- if not closed :
98- # In some cases (like on Python 3) a file opened for
99- # appending still shows a mode of 'r+', hence the extra
100- # check for the append case
101- if ((mode == 'append' and fmode not in ('ab+' , 'rb+' )) or
102- (mode != 'append' and PYTHON_MODES [mode ] != fmode )):
103- raise ValueError (
104- "Input mode '%s' (%s) does not match mode of the "
105- "input file (%s)." % (mode , PYTHON_MODES [mode ], fmode ))
106- self .__file = fileobj
107- elif isfile (fileobj ):
108- self .__file = fileobj_open (self .name , PYTHON_MODES [mode ])
109- # Return to the beginning of the file--in Python 3 when
110- # opening in append mode the file pointer is at the end of
111- # the file
112- self .__file .seek (0 )
113- else :
114- self .__file = gzip .open (self .name , PYTHON_MODES [mode ])
94+ self ._open_fileobj (fileobj , mode )
11595 elif isinstance (fileobj , basestring ):
116- if os .path .exists (self .name ):
117- with fileobj_open (self .name , 'rb' ) as f :
118- magic = f .read (4 )
119- else :
120- magic = '' .encode ('raw-unicode-escape' )
121- ext = os .path .splitext (self .name )[1 ]
122- if ext == '.gz' or magic .startswith (GZIP_MAGIC ):
123- # Handle gzip files
124- if mode in ['update' , 'append' ]:
125- raise IOError (
126- "Writing to gzipped fits files is not currently "
127- "supported" )
128- self .__file = gzip .open (self .name )
129- self .compression = 'gzip'
130- elif ext == '.zip' or magic .startswith (PKZIP_MAGIC ):
131- # Handle zip files
132- if mode in ['update' , 'append' ]:
133- raise IOError (
134- "Writing to zipped fits files is not currently "
135- "supported" )
136- zfile = zipfile .ZipFile (self .name )
137- namelist = zfile .namelist ()
138- if len (namelist ) != 1 :
139- raise IOError (
140- "Zip files with multiple members are not supported." )
141- self .__file = tempfile .NamedTemporaryFile (suffix = '.fits' )
142- self .__file .write (zfile .read (namelist [0 ]))
143- zfile .close ()
144- self .compression = 'zip'
145- else :
146- self .__file = fileobj_open (self .name , PYTHON_MODES [mode ])
147- # Make certain we're back at the beginning of the file
148- self .__file .seek (0 )
96+ self ._open_filename (fileobj , mode )
14997 else :
150- # We are dealing with a file like object.
151- # Assume it is open.
152- self .file_like = True
153- self .__file = fileobj
154-
155- # If there is not seek or tell methods then set the mode to
156- # output streaming.
157- if (not hasattr (self .__file , 'seek' ) or
158- not hasattr (self .__file , 'tell' )):
159- self .mode = mode = 'ostream'
160-
161- if (self .mode in ('copyonwrite' , 'update' , 'append' ) and
162- not hasattr (self .__file , 'write' )):
163- raise IOError ("File-like object does not have a 'write' "
164- "method, required for mode '%s'."
165- % self .mode )
166-
167- if (self .mode in ('readonly' , 'denywrite' ) and
168- not hasattr (self .__file , 'read' )):
169- raise IOError ("File-like object does not have a 'read' "
170- "method, required for mode %r."
171- % self .mode )
98+ self ._open_filelike (fileobj , mode )
17299
173100 if isinstance (fileobj , gzip .GzipFile ):
174101 self .compression = 'gzip'
@@ -342,3 +269,86 @@ def close(self):
342269 self .__file .close ()
343270
344271 self .closed = True
272+
273+ def _open_fileobj (self , fileobj , mode ):
274+ """Open a FITS file from a file object or a GzipFile object."""
275+
276+ closed = fileobj_closed (fileobj )
277+ fmode = fileobj_mode (fileobj ) or PYTHON_MODES [mode ]
278+
279+ if not closed :
280+ # In some cases (like on Python 3) a file opened for appending
281+ # still shows a mode of 'r+', hence the extra check for the append
282+ # case
283+ if ((mode == 'append' and fmode not in ('ab+' , 'rb+' )) or
284+ (mode != 'append' and PYTHON_MODES [mode ] != fmode )):
285+ raise ValueError (
286+ "Input mode '%s' (%s) does not match mode of the "
287+ "input file (%s)." % (mode , PYTHON_MODES [mode ], fmode ))
288+ self .__file = fileobj
289+ elif isfile (fileobj ):
290+ self .__file = fileobj_open (self .name , PYTHON_MODES [mode ])
291+ # Return to the beginning of the file--in Python 3 when opening in
292+ # append mode the file pointer is at the end of the file
293+ self .__file .seek (0 )
294+ else :
295+ self .__file = gzip .open (self .name , PYTHON_MODES [mode ])
296+
297+ def _open_filelike (self , fileobj , mode ):
298+ """Open a FITS file from a file-like object, i.e. one that has
299+ read and/or write methods.
300+ """
301+
302+ self .file_like = True
303+ self .__file = fileobj
304+
305+ # If there is not seek or tell methods then set the mode to
306+ # output streaming.
307+ if (not hasattr (self .__file , 'seek' ) or
308+ not hasattr (self .__file , 'tell' )):
309+ self .mode = mode = 'ostream'
310+
311+ if (self .mode in ('copyonwrite' , 'update' , 'append' ) and
312+ not hasattr (self .__file , 'write' )):
313+ raise IOError ("File-like object does not have a 'write' "
314+ "method, required for mode '%s'."
315+ % self .mode )
316+
317+ if (self .mode in ('readonly' , 'denywrite' ) and
318+ not hasattr (self .__file , 'read' )):
319+ raise IOError ("File-like object does not have a 'read' "
320+ "method, required for mode %r."
321+ % self .mode )
322+
323+ def _open_filename (self , filename , mode ):
324+ """Open a FITS file from a filename string."""
325+
326+ if os .path .exists (self .name ):
327+ with fileobj_open (self .name , 'rb' ) as f :
328+ magic = f .read (4 )
329+ else :
330+ magic = '' .encode ('raw-unicode-escape' )
331+ ext = os .path .splitext (self .name )[1 ]
332+ if ext == '.gz' or magic .startswith (GZIP_MAGIC ):
333+ # Handle gzip files
334+ self .__file = gzip .open (self .name , PYTHON_MODES [mode ])
335+ self .compression = 'gzip'
336+ elif ext == '.zip' or magic .startswith (PKZIP_MAGIC ):
337+ # Handle zip files
338+ if mode in ['update' , 'append' ]:
339+ raise IOError (
340+ "Writing to zipped fits files is not currently "
341+ "supported" )
342+ zfile = zipfile .ZipFile (self .name )
343+ namelist = zfile .namelist ()
344+ if len (namelist ) != 1 :
345+ raise IOError (
346+ "Zip files with multiple members are not supported." )
347+ self .__file = tempfile .NamedTemporaryFile (suffix = '.fits' )
348+ self .__file .write (zfile .read (namelist [0 ]))
349+ zfile .close ()
350+ self .compression = 'zip'
351+ else :
352+ self .__file = fileobj_open (self .name , PYTHON_MODES [mode ])
353+ # Make certain we're back at the beginning of the file
354+ self .__file .seek (0 )
0 commit comments