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 decrypt
(self, name, mode="r", pwd=None, *, force_zip64=False)
| 1682 | return fp.read() |
| 1683 | |
| 1684 | def open(self, name, mode="r", pwd=None, *, force_zip64=False): |
| 1685 | """Return file-like object for 'name'. |
| 1686 | |
| 1687 | name is a string for the file name within the ZIP file, or a ZipInfo |
| 1688 | object. |
| 1689 | |
| 1690 | mode should be 'r' to read a file already in the ZIP file, or 'w' to |
| 1691 | write to a file newly added to the archive. |
| 1692 | |
| 1693 | pwd is the password to decrypt files (only used for reading). |
| 1694 | |
| 1695 | When writing, if the file size is not known in advance but may exceed |
| 1696 | 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large |
| 1697 | files. If the size is known in advance, it is best to pass a ZipInfo |
| 1698 | instance for name, with zinfo.file_size set. |
| 1699 | """ |
| 1700 | if mode not in {"r", "w"}: |
| 1701 | raise ValueError('open() requires mode "r" or "w"') |
| 1702 | if pwd and (mode == "w"): |
| 1703 | raise ValueError("pwd is only supported for reading files") |
| 1704 | if not self.fp: |
| 1705 | raise ValueError( |
| 1706 | "Attempt to use ZIP archive that was already closed") |
| 1707 | |
| 1708 | # Make sure we have an info object |
| 1709 | if isinstance(name, ZipInfo): |
| 1710 | # 'name' is already an info object |
| 1711 | zinfo = name |
| 1712 | elif mode == 'w': |
| 1713 | zinfo = ZipInfo(name) |
| 1714 | zinfo.compress_type = self.compression |
| 1715 | zinfo.compress_level = self.compresslevel |
| 1716 | else: |
| 1717 | # Get info object for name |
| 1718 | zinfo = self.getinfo(name) |
| 1719 | |
| 1720 | if mode == 'w': |
| 1721 | return self._open_to_write(zinfo, force_zip64=force_zip64) |
| 1722 | |
| 1723 | if self._writing: |
| 1724 | raise ValueError("Can't read from the ZIP file while there " |
| 1725 | "is an open writing handle on it. " |
| 1726 | "Close the writing handle before trying to read.") |
| 1727 | |
| 1728 | # Open for reading: |
| 1729 | self._fileRefCnt += 1 |
| 1730 | zef_file = _SharedFile(self.fp, zinfo.header_offset, |
| 1731 | self._fpclose, self._lock, lambda: self._writing) |
| 1732 | try: |
| 1733 | # Skip the file header: |
| 1734 | fheader = zef_file.read(sizeFileHeader) |
| 1735 | if len(fheader) != sizeFileHeader: |
| 1736 | raise BadZipFile("Truncated file header") |
| 1737 | fheader = struct.unpack(structFileHeader, fheader) |
| 1738 | if fheader[_FH_SIGNATURE] != stringFileHeader: |
| 1739 | raise BadZipFile("Bad magic number for file header") |
| 1740 | |
| 1741 | fname = zef_file.read(fheader[_FH_FILENAME_LENGTH]) |
no test coverage detected