diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py index 1e1854be7109b6..32a7bbf76d79fd 100644 --- a/Lib/test/test_zipfile.py +++ b/Lib/test/test_zipfile.py @@ -318,6 +318,14 @@ def test_writestr_compresslevel(self): self.assertEqual(b_info.compress_type, self.compression) self.assertEqual(b_info._compresslevel, 2) + def test_writestr_permission(self): + zipfp = zipfile.ZipFile(TESTFN2, "w") + zipfp.writestr("b.txt", "hello world", file_perm=0o755) + b_info = zipfp.getinfo('b.txt') + perm = oct(b_info.external_attr >> 16) + assert perm == '0o755' + + def test_read_return_size(self): # Issue #9837: ZipExtFile.read() shouldn't return more bytes # than requested. diff --git a/Lib/zipfile.py b/Lib/zipfile.py index b0afb9da942b12..3a5df13a54ca0f 100644 --- a/Lib/zipfile.py +++ b/Lib/zipfile.py @@ -1751,12 +1751,14 @@ def write(self, filename, arcname=None, shutil.copyfileobj(src, dest, 1024*8) def writestr(self, zinfo_or_arcname, data, - compress_type=None, compresslevel=None): + compress_type=None, compresslevel=None, + file_perm=0o600): """Write a file into the archive. The contents is 'data', which may be either a 'str' or a 'bytes' instance; if it is a 'str', it is encoded as UTF-8 first. 'zinfo_or_arcname' is either a ZipInfo instance or - the name of the file in the archive.""" + the name of the file in the archive. Default permission is set to 600 + (rw-------) but can be specified with file_perm.""" if isinstance(data, str): data = data.encode("utf-8") if not isinstance(zinfo_or_arcname, ZipInfo): @@ -1768,7 +1770,7 @@ def writestr(self, zinfo_or_arcname, data, zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x zinfo.external_attr |= 0x10 # MS-DOS directory flag else: - zinfo.external_attr = 0o600 << 16 # ?rw------- + zinfo.external_attr = file_perm << 16 # ?rw------- else: zinfo = zinfo_or_arcname diff --git a/Misc/NEWS.d/next/Library/2019-11-22-15-31-12.bpo-38886.yLQRPS.rst b/Misc/NEWS.d/next/Library/2019-11-22-15-31-12.bpo-38886.yLQRPS.rst new file mode 100644 index 00000000000000..68135cca6f81f1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-11-22-15-31-12.bpo-38886.yLQRPS.rst @@ -0,0 +1,2 @@ +add option to zipfile.writestr to open permissions: new optional argument +to allow user to choose permission of written file \ No newline at end of file