diff --git a/Lib/gzip.py b/Lib/gzip.py --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -1,19 +1,20 @@ """Functions that read and write gzipped files. The user of the file doesn't have to worry about the compression, but random access is not allowed.""" # based on Andrew Kuchling's minigzip.py distributed with the zlib module import struct, sys, time, os import zlib +import pathlib import builtins import io import _compression __all__ = ["GzipFile", "open", "compress", "decompress"] FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16 READ, WRITE = 1, 2 @@ -42,21 +43,21 @@ def open(filename, mode="rb", compressle raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if errors is not None: raise ValueError("Argument 'errors' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode") gz_mode = mode.replace("t", "") - if isinstance(filename, (str, bytes)): + if isinstance(filename, (str, bytes, os.PathLike)): binary_file = GzipFile(filename, gz_mode, compresslevel) elif hasattr(filename, "read") or hasattr(filename, "write"): binary_file = GzipFile(None, gz_mode, compresslevel, filename) else: raise TypeError("filename must be a str or bytes object, or a file") if "t" in mode: return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file @@ -165,21 +166,21 @@ class GzipFile(_compression.BaseStream): filename = getattr(fileobj, 'name', '') if not isinstance(filename, (str, bytes)): filename = '' if mode is None: mode = getattr(fileobj, 'mode', 'rb') if mode.startswith('r'): self.mode = READ raw = _GzipReader(fileobj) self._buffer = io.BufferedReader(raw) - self.name = filename + self.name = os.fspath(filename) elif mode.startswith(('w', 'a', 'x')): self.mode = WRITE self._init_write(filename) self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0) self._write_mtime = mtime diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py --- a/Lib/test/test_gzip.py +++ b/Lib/test/test_gzip.py @@ -1,17 +1,18 @@ """Test script for the gzip module. """ import unittest from test import support from test.support import bigmemtest, _4G import os +import pathlib import io import struct import array gzip = support.import_module('gzip') data1 = b""" int length=DEFAULTALLOC, err = Z_OK; PyObject *RetVal; int flushmode = Z_FINISH; unsigned long start_total_out; @@ -60,20 +61,29 @@ class TestGzip(BaseTest): # Try flush and fileno. f.flush() f.fileno() if hasattr(os, 'fsync'): os.fsync(f.fileno()) f.close() # Test multiple close() calls. f.close() + def test_write_read_with_pathlike_file(self): + with gzip.GzipFile(pathlib.Path(self.filename), 'wb') as f: + f.write(data1 * 50) + with gzip.GzipFile(pathlib.Path(self.filename), 'r') as f: + d = f.read() + self.assertEqual(d, data1*50) + # check name attribute + self.assertTrue(isinstance(f.name, str), "f.name is of type %r" % type(f.name)) + # The following test_write_xy methods test that write accepts # the corresponding bytes-like object type as input # and that the data written equals bytes(xy) in all cases. def test_write_memoryview(self): self.write_and_read_back(memoryview(data1 * 50)) m = memoryview(bytes(range(256))) data = m.cast('B', shape=[8,8,4]) self.write_and_read_back(data) def test_write_bytearray(self): @@ -514,20 +524,29 @@ class TestOpen(BaseTest): with self.assertRaises(FileExistsError): gzip.open(self.filename, "xb") support.unlink(self.filename) with gzip.open(self.filename, "xb") as f: f.write(uncompressed) with open(self.filename, "rb") as f: file_data = gzip.decompress(f.read()) self.assertEqual(file_data, uncompressed) + def test_pathlike_file(self): + uncompressed = data1 * 50 + + with gzip.open(pathlib.Path(self.filename), "wb") as f: + f.write(uncompressed) + with open(pathlib.Path(self.filename), "rb") as f: + file_data = gzip.decompress(f.read()) + self.assertEqual(file_data, uncompressed) + def test_implicit_binary_modes(self): # Test implicit binary modes (no "b" or "t" in mode string). uncompressed = data1 * 50 with gzip.open(self.filename, "w") as f: f.write(uncompressed) with open(self.filename, "rb") as f: file_data = gzip.decompress(f.read()) self.assertEqual(file_data, uncompressed)