File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -210,6 +210,13 @@ def __repr__(self):
210210 s = repr (fileobj )
211211 return '<gzip ' + s [1 :- 1 ] + ' ' + hex (id (self )) + '>'
212212
213+ def _check_closed (self ):
214+ """Raises a ValueError if the underlying file object has been closed.
215+
216+ """
217+ if self .closed :
218+ raise ValueError ('I/O operation on closed file.' )
219+
213220 def _init_write (self , filename ):
214221 self .name = filename
215222 self .crc = zlib .crc32 (b"" ) & 0xffffffff
@@ -288,6 +295,7 @@ def _read_gzip_header(self):
288295 self ._add_read_data (uncompress )
289296
290297 def write (self ,data ):
298+ self ._check_closed ()
291299 if self .mode != WRITE :
292300 import errno
293301 raise IOError (errno .EBADF , "write() on read-only GzipFile object" )
@@ -308,6 +316,7 @@ def write(self,data):
308316 return len (data )
309317
310318 def read (self , size = - 1 ):
319+ self ._check_closed ()
311320 if self .mode != READ :
312321 import errno
313322 raise IOError (errno .EBADF , "read() on write-only GzipFile object" )
@@ -457,6 +466,7 @@ def close(self):
457466 self .myfileobj = None
458467
459468 def flush (self ,zlib_mode = zlib .Z_SYNC_FLUSH ):
469+ self ._check_closed ()
460470 if self .mode == WRITE :
461471 # Ensure the compressor's buffer is flushed
462472 self .fileobj .write (self .compress .flush (zlib_mode ))
Original file line number Diff line number Diff line change @@ -62,6 +62,28 @@ def test_read(self):
6262 f = gzip .GzipFile (self .filename , 'r' ) ; d = f .read () ; f .close ()
6363 self .assertEqual (d , data1 * 50 )
6464
65+ def test_io_on_closed_object (self ):
66+ # Test that I/O operations on closed GzipFile objects raise a
67+ # ValueError, just like the corresponding functions on file objects.
68+
69+ # Write to a file, open it for reading, then close it.
70+ self .test_write ()
71+ f = gzip .GzipFile (self .filename , 'r' )
72+ f .close ()
73+ with self .assertRaises (ValueError ):
74+ f .read (1 )
75+ with self .assertRaises (ValueError ):
76+ f .seek (0 )
77+ with self .assertRaises (ValueError ):
78+ f .tell ()
79+ # Open the file for writing, then close it.
80+ f = gzip .GzipFile (self .filename , 'w' )
81+ f .close ()
82+ with self .assertRaises (ValueError ):
83+ f .write (b'' )
84+ with self .assertRaises (ValueError ):
85+ f .flush ()
86+
6587 def test_append (self ):
6688 self .test_write ()
6789 # Append to the previous file
Original file line number Diff line number Diff line change @@ -88,6 +88,9 @@ Core and Builtins
8888Library
8989-------
9090
91+ - Issue #9759: GzipFile now raises ValueError when an operation is attempted
92+ after the file is closed. Patch by Jeffrey Finkelstein.
93+
9194- Issue #9042: Fix interaction of custom translation classes and caching in
9295 gettext.
9396
You can’t perform that action at this time.
0 commit comments