Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 103e811

Browse files
committed
Fix GzipFile's handling of filenames given as bytes objects.
1 parent f29ec4b commit 103e811

3 files changed

Lines changed: 20 additions & 4 deletions

File tree

Lib/gzip.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,9 +159,8 @@ def __init__(self, filename=None, mode=None,
159159
if fileobj is None:
160160
fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
161161
if filename is None:
162-
if hasattr(fileobj, 'name') and isinstance(fileobj.name, str):
163-
filename = fileobj.name
164-
else:
162+
filename = getattr(fileobj, 'name', '')
163+
if not isinstance(filename, (str, bytes)):
165164
filename = ''
166165
if mode is None:
167166
if hasattr(fileobj, 'mode'): mode = fileobj.mode
@@ -236,7 +235,8 @@ def _write_gzip_header(self):
236235
# RFC 1952 requires the FNAME field to be Latin-1. Do not
237236
# include filenames that cannot be represented that way.
238237
fname = os.path.basename(self.name)
239-
fname = fname.encode('latin-1')
238+
if not isinstance(fname, bytes):
239+
fname = fname.encode('latin-1')
240240
if fname.endswith(b'.gz'):
241241
fname = fname[:-3]
242242
except UnicodeEncodeError:

Lib/test/test_gzip.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,20 @@ def test_fileobj_from_fdopen(self):
331331
with gzip.GzipFile(fileobj=f, mode="w") as g:
332332
pass
333333

334+
def test_bytes_filename(self):
335+
str_filename = self.filename
336+
try:
337+
bytes_filename = str_filename.encode("ascii")
338+
except UnicodeEncodeError:
339+
self.skipTest("Temporary file name needs to be ASCII")
340+
with gzip.GzipFile(bytes_filename, "wb") as f:
341+
f.write(data1 * 50)
342+
with gzip.GzipFile(bytes_filename, "rb") as f:
343+
self.assertEqual(f.read(), data1 * 50)
344+
# Sanity check that we are actually operating on the right file.
345+
with gzip.GzipFile(str_filename, "rb") as f:
346+
self.assertEqual(f.read(), data1 * 50)
347+
334348
# Testing compress/decompress shortcut functions
335349

336350
def test_compress(self):

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ Core and Builtins
7070
Library
7171
-------
7272

73+
- Fix GzipFile's handling of filenames given as bytes objects.
74+
7375
- Issue #15101: Make pool finalizer avoid joining current thread.
7476

7577
- Issue #15036: Mailbox no longer throws an error if a flush is done

0 commit comments

Comments
 (0)