Return file-like object for 'name'. name is a string for the file name within the ZIP file, or a ZipInfo object. mode should be 'r' to read a file already in the ZIP file, or 'w' to write to a file newly added to the archive. pwd is the password to
(self, name, mode="r", pwd=None, *, force_zip64=False)
| 1527 | return fp.read() |
| 1528 | |
| 1529 | def open(self, name, mode="r", pwd=None, *, force_zip64=False): |
| 1530 | """Return file-like object for 'name'. |
| 1531 | |
| 1532 | name is a string for the file name within the ZIP file, or a ZipInfo |
| 1533 | object. |
| 1534 | |
| 1535 | mode should be 'r' to read a file already in the ZIP file, or 'w' to |
| 1536 | write to a file newly added to the archive. |
| 1537 | |
| 1538 | pwd is the password to decrypt files (only used for reading). |
| 1539 | |
| 1540 | When writing, if the file size is not known in advance but may exceed |
| 1541 | 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large |
| 1542 | files. If the size is known in advance, it is best to pass a ZipInfo |
| 1543 | instance for name, with zinfo.file_size set. |
| 1544 | """ |
| 1545 | if mode not in {"r", "w"}: |
| 1546 | raise ValueError('open() requires mode "r" or "w"') |
| 1547 | if pwd and (mode == "w"): |
| 1548 | raise ValueError("pwd is only supported for reading files") |
| 1549 | if not self.fp: |
| 1550 | raise ValueError( |
| 1551 | "Attempt to use ZIP archive that was already closed") |
| 1552 | |
| 1553 | # Make sure we have an info object |
| 1554 | if isinstance(name, ZipInfo): |
| 1555 | # 'name' is already an info object |
| 1556 | zinfo = name |
| 1557 | elif mode == 'w': |
| 1558 | zinfo = ZipInfo(name) |
| 1559 | zinfo.compress_type = self.compression |
| 1560 | zinfo._compresslevel = self.compresslevel |
| 1561 | else: |
| 1562 | # Get info object for name |
| 1563 | zinfo = self.getinfo(name) |
| 1564 | |
| 1565 | if mode == 'w': |
| 1566 | return self._open_to_write(zinfo, force_zip64=force_zip64) |
| 1567 | |
| 1568 | if self._writing: |
| 1569 | raise ValueError("Can't read from the ZIP file while there " |
| 1570 | "is an open writing handle on it. " |
| 1571 | "Close the writing handle before trying to read.") |
| 1572 | |
| 1573 | # Open for reading: |
| 1574 | self._fileRefCnt += 1 |
| 1575 | zef_file = _SharedFile(self.fp, zinfo.header_offset, |
| 1576 | self._fpclose, self._lock, lambda: self._writing) |
| 1577 | try: |
| 1578 | # Skip the file header: |
| 1579 | fheader = zef_file.read(sizeFileHeader) |
| 1580 | if len(fheader) != sizeFileHeader: |
| 1581 | raise BadZipFile("Truncated file header") |
| 1582 | fheader = struct.unpack(structFileHeader, fheader) |
| 1583 | if fheader[_FH_SIGNATURE] != stringFileHeader: |
| 1584 | raise BadZipFile("Bad magic number for file header") |
| 1585 | |
| 1586 | fname = zef_file.read(fheader[_FH_FILENAME_LENGTH]) |
no test coverage detected