当前位置: 首页>>代码示例>>Python>>正文


Python zipfile.BadZipFile方法代码示例

本文整理汇总了Python中zipfile.BadZipFile方法的典型用法代码示例。如果您正苦于以下问题:Python zipfile.BadZipFile方法的具体用法?Python zipfile.BadZipFile怎么用?Python zipfile.BadZipFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块zipfile的用法示例。

在下文中一共展示了zipfile.BadZipFile方法的26个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _read_meta

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _read_meta(source) -> Tuple[ZipFile, PluginMeta]:
        try:
            file = ZipFile(source)
            data = file.read("maubot.yaml")
        except FileNotFoundError as e:
            raise MaubotZipMetaError("Maubot plugin not found") from e
        except BadZipFile as e:
            raise MaubotZipMetaError("File is not a maubot plugin") from e
        except KeyError as e:
            raise MaubotZipMetaError("File does not contain a maubot plugin definition") from e
        try:
            meta_dict = yaml.load(data)
        except (YAMLError, KeyError, IndexError, ValueError) as e:
            raise MaubotZipMetaError("Maubot plugin definition file is not valid YAML") from e
        try:
            meta = PluginMeta.deserialize(meta_dict)
        except SerializerError as e:
            raise MaubotZipMetaError("Maubot plugin definition in file is invalid") from e
        return file, meta 
开发者ID:maubot,项目名称:maubot,代码行数:21,代码来源:zip.py


示例2: extract_template

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def extract_template(package_path):
    print("package_path" + package_path)
    root_path = os.path.join(tempfile.gettempdir(), "salesforcexytools")
    try:
        zfile = zipfile.ZipFile(package_path, 'r')
        for filename in zfile.namelist():
            if filename.endswith('/'): continue
            if filename.endswith('.py'): continue
            if filename.startswith("templates/"):
                f = os.path.join(root_path, filename)
                if not os.path.exists(os.path.dirname(f)):
                    os.makedirs(os.path.dirname(f))
                with open(f, "wb") as fp:
                    fp.write(zfile.read(filename))
    except zipfile.BadZipFile as ex:
        print(str(ex))
        return 
开发者ID:exiahuang,项目名称:SalesforceXyTools,代码行数:19,代码来源:template.py


示例3: _loadMetadata

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _loadMetadata(file_name: str) -> Dict[str, Dict[str, Any]]:
        result = dict()  # type: Dict[str, Dict[str, Any]]
        try:
            archive = zipfile.ZipFile(file_name, "r")
        except zipfile.BadZipFile:
            Logger.logException("w", "Unable to retrieve metadata from {fname}: 3MF archive is corrupt.".format(fname = file_name))
            return result

        metadata_files = [name for name in archive.namelist() if name.endswith("plugin_metadata.json")]


        for metadata_file in metadata_files:
            try:
                plugin_id = metadata_file.split("/")[0]
                result[plugin_id] = json.loads(archive.open("%s/plugin_metadata.json" % plugin_id).read().decode("utf-8"))
            except Exception:
                Logger.logException("w", "Unable to retrieve metadata for %s", metadata_file)

        return result 
开发者ID:Ultimaker,项目名称:Cura,代码行数:21,代码来源:ThreeMFWorkspaceReader.py


示例4: extract_zip

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def extract_zip(filename: str, destination_dir: str):
    """ Extracts a zipped file

    Parameters
    ----------
    filename : str
        The zipped filename
    destination_dir : str
        The directory where the zipped will be placed

    """
    msg_printer = Printer()
    try:
        with msg_printer.loading(f"Unzipping file {filename} to {destination_dir}"):
            stdout.flush()
            with zipfile.ZipFile(filename, "r") as z:
                z.extractall(destination_dir)

        msg_printer.good(f"Finished extraction {filename} to {destination_dir}")
    except zipfile.BadZipFile:
        msg_printer.fail(f"Couldnot extract {filename} to {destination_dir}") 
开发者ID:abhinavkashyap,项目名称:sciwing,代码行数:23,代码来源:common.py


示例5: test_empty_zipfile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_empty_zipfile(self):
        # Check that creating a file in 'w' or 'a' mode and closing without
        # adding any files to the archives creates a valid empty ZIP file
        zipf = zipfile.ZipFile(TESTFN, mode="w")
        zipf.close()
        try:
            zipf = zipfile.ZipFile(TESTFN, mode="r")
        except zipfile.BadZipFile:
            self.fail("Unable to create empty ZIP file in 'w' mode")

        zipf = zipfile.ZipFile(TESTFN, mode="a")
        zipf.close()
        try:
            zipf = zipfile.ZipFile(TESTFN, mode="r")
        except:
            self.fail("Unable to create empty ZIP file in 'a' mode") 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_zipfile.py


示例6: test_read_with_bad_crc

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_read_with_bad_crc(self):
        """Tests that files with bad CRCs raise a BadZipFile exception when read."""
        zipdata = self.zip_with_bad_crc

        # Using ZipFile.read()
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')

        # Using ZipExtFile.read()
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            with zipf.open('afile', 'r') as corrupt_file:
                self.assertRaises(zipfile.BadZipFile, corrupt_file.read)

        # Same with small reads (in order to exercise the buffering logic)
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            with zipf.open('afile', 'r') as corrupt_file:
                corrupt_file.MIN_READ_SIZE = 2
                with self.assertRaises(zipfile.BadZipFile):
                    while corrupt_file.read(2):
                        pass 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:test_zipfile.py


示例7: import_has_conflicts

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def import_has_conflicts(archive):
    """Verify if the `archive` files conflicts with the user presets.

    :param archive: path of the archive to analyze
    :type archive: str
    :rtype: bool
    """
    try:
        with ZipFile(archive) as archive:
            for member in archive.namelist():
                if preset_exists(member):
                    return True
    except(OSError, BadZipFile) as e:
        raise PresetImportError(str(e))

    return False 
开发者ID:FrancescoCeruti,项目名称:linux-show-player,代码行数:18,代码来源:lib.py


示例8: import_conflicts

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def import_conflicts(archive):
    """Return a list of conflicts between `archive` files and user presets.

    :param archive: path of the archive to analyze
    :type archive: str
    """
    conflicts = []

    try:
        with ZipFile(archive) as archive:
            for member in archive.namelist():
                if preset_exists(member):
                    conflicts.append(member)
    except(OSError, BadZipFile) as e:
        raise PresetImportError(str(e))

    return conflicts 
开发者ID:FrancescoCeruti,项目名称:linux-show-player,代码行数:19,代码来源:lib.py


示例9: _getPluginIdFromFile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _getPluginIdFromFile(self, filename: str) -> Optional[str]:
        plugin_id = None
        try:
            with zipfile.ZipFile(filename, "r") as zip_ref:
                for file_info in zip_ref.infolist():
                    if file_info.filename.endswith("/"):
                        plugin_id = file_info.filename.strip("/")
                        break
        except zipfile.BadZipFile:
            Logger.logException("e", "Failed to load plug-in file. The zip archive seems to be corrupt.")
            return None  # Signals that loading this failed.
        except FileNotFoundError:
            Logger.logException("e", "Failed to load plug-in file as we were unable to find it.")
            return None  # Signals that loading this failed.
        return plugin_id

    #   Returns a list of all possible plugin ids in the plugin locations: 
开发者ID:Ultimaker,项目名称:Uranium,代码行数:19,代码来源:PluginRegistry.py


示例10: getPackageLicense

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def getPackageLicense(self, filename: str) -> Optional[str]:
        license_string = None
        def is_license(zipinfo: zipfile.ZipInfo) -> bool:
            return os.path.basename(zipinfo.filename).startswith("LICENSE")
        try:
            with zipfile.ZipFile(filename) as archive:
                # Go through all the files and use the first successful read as the result
                license_files = sorted(filter(is_license, archive.infolist()), key = lambda x: len(x.filename))  # Find the one with the shortest path.
                for file_info in license_files:
                    Logger.log("d", "Found potential license file '{filename}'".format(filename = file_info.filename))
                    try:
                        with archive.open(file_info.filename, "r") as f:
                            data = f.read()
                        license_string = data.decode("utf-8")
                        break
                    except:
                        Logger.logException("e", "Failed to load potential license file '%s' as text file.", file_info.filename)
                        license_string = None
        except zipfile.BadZipFile as e:
            Logger.error("Package is corrupt: {err}".format(err = str(e)))
            license_string = None
        except UnicodeDecodeError:
            Logger.error("Package filenames are not UTF-8 encoded! Encoding unknown.")
            license_string = None
        return license_string 
开发者ID:Ultimaker,项目名称:Uranium,代码行数:27,代码来源:PackageManager.py


示例11: read_sheets

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def read_sheets(self):
        try:
            self.workbook = openpyxl.load_workbook(self.input_name, data_only=True)
        except BadZipFile as e:  # noqa
            # TODO when we have python3 only add 'from e' to show exception chain
            raise BadXLSXZipFile(
                "The supplied file has extension .xlsx but isn't an XLSX file."
            )

        self.sheet_names_map = OrderedDict(
            (sheet_name, sheet_name) for sheet_name in self.workbook.sheetnames
        )
        if self.include_sheets:
            for sheet in list(self.sheet_names_map):
                if sheet not in self.include_sheets:
                    self.sheet_names_map.pop(sheet)
        for sheet in self.exclude_sheets or []:
            self.sheet_names_map.pop(sheet, None)

        sheet_names = list(sheet for sheet in self.sheet_names_map.keys())
        self.sub_sheet_names = sheet_names
        self.configure_sheets() 
开发者ID:OpenDataServices,项目名称:flatten-tool,代码行数:24,代码来源:input.py


示例12: test_open_corrupt_container

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_open_corrupt_container(self):
        with self.assertRaises(FileNotFoundError):
            DataContainer('test-container.data.zip')

        with open("test-container.data.zip", "w+") as f:
            f.write("INVALID_ZIP_DATA")

        with self.assertRaises(zipfile.BadZipFile):
            DataContainer('test-container.data.zip')

        os.unlink('test-container.data.zip')

        with zipfile.ZipFile('test-container.data.zip', 'w') as f:
            f.writestr('bad.txt', 'BAD')

        with self.assertRaises(MetadataNotFoundError):
            DataContainer('test-container.data.zip')

        os.unlink('test-container.data.zip') 
开发者ID:a2i2,项目名称:surround,代码行数:21,代码来源:container_test.py


示例13: _process_md5

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _process_md5(md5: str) -> bool:
    """Download the given file from CarbonBlack and upload to S3, returning True if successful."""
    try:
        binary = CARBON_BLACK.select(Binary, md5)
        _upload_to_s3(binary)
        return True
    except zipfile.BadZipFile:
        LOGGER.exception('[BadZipFile] Error downloading %s', md5)
        LOGGER.info('This md5 is invalid and will not retried')
        return False
    except (BotoCoreError, ServerError):
        LOGGER.exception('Error downloading %s', md5)
        LOGGER.error(
            'A temporary error was encountered during downloading. This md5 will be '
            'retried at a later time.'
        )
        raise
    except ObjectNotFoundError:
        LOGGER.exception('Error downloading %s', md5)
        LOGGER.info(
            'This may be caused due to a race condition where the requested binary is not yet '
            'available for download from the server. This binary will be retried at a later time.'
        )
        raise 
开发者ID:airbnb,项目名称:binaryalert,代码行数:26,代码来源:main.py


示例14: get_apk_id

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def get_apk_id(apkfile):
    """Extract identification information from APK.

    Androguard is preferred since it is more reliable and a lot
    faster.  Occasionally, when androguard can't get the info from the
    APK, aapt still can.  So aapt is also used as the final fallback
    method.

    :param apkfile: path to an APK file.
    :returns: triplet (appid, version code, version name)

    """
    if use_androguard():
        try:
            return get_apk_id_androguard(apkfile)
        except zipfile.BadZipFile as e:
            logging.error(apkfile + ': ' + str(e))
            if 'aapt' in config:
                return get_apk_id_aapt(apkfile)
    else:
        return get_apk_id_aapt(apkfile) 
开发者ID:f-droid,项目名称:fdroidserver,代码行数:23,代码来源:common.py


示例15: unzip_archive

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def unzip_archive(archive_path):
    if os.path.exists(archive_path):
        set_import_status('Unzipping model')
        import zipfile
        try:
            zip_ref = zipfile.ZipFile(archive_path, 'r')
            extract_dir = os.path.dirname(archive_path)
            zip_ref.extractall(extract_dir)
            zip_ref.close()
        except zipfile.BadZipFile:
            print('Error when dezipping file')
            os.remove(archive_path)
            print('Invaild zip. Try again')
            set_import_status('')
            return None, None

        gltf_file = os.path.join(extract_dir, 'scene.gltf')
        return gltf_file, archive_path

    else:
        print('ERROR: archive doesn\'t exist') 
开发者ID:sketchfab,项目名称:blender-plugin,代码行数:23,代码来源:__init__.py


示例16: _getFromZipFile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _getFromZipFile(self, getter):
        plainsrc = self.decryptor(self.enczfsrc)
        try:
            z = ZipFile(BytesIO(plainsrc))
        except BadZipFile as ex:
            logging.error('Invalid zip contents (%s) for source hash %s: %s',
                          str(plainsrc) if not plainsrc or len(plainsrc) < 100
                          else str(plainsrc[:97]) + '...',
                          self.srcHash, ex)
            raise
        try:
            return getter(z)
        finally:
            # Try to be hygenic.  This is an interpreted language, but do what we can...
            z.close()
            del z
            # Strings in Python are typically immutable; attempts to
            # modify the string will likely just make more copies, so just
            # tell the interpreter to get rid of the main copy asap.
            del plainsrc 
开发者ID:thespianpy,项目名称:Thespian,代码行数:22,代码来源:sourceLoader.py


示例17: _merge_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _merge_file(self, byte_io: typing.IO[bytes]) -> None:
        """Read and merge host files.

        Args:
            byte_io: The BytesIO object of the completed download.
        """
        error_count = 0
        line_count = 0
        try:
            f = get_fileobj(byte_io)
        except (OSError, zipfile.BadZipFile, zipfile.LargeZipFile,
                LookupError) as e:
            message.error("adblock: Error while reading {}: {} - {}".format(
                byte_io.name, e.__class__.__name__, e))
            return

        for line in f:
            line_count += 1
            try:
                self._blocked_hosts |= self._read_hosts_line(line)
            except UnicodeDecodeError:
                logger.error("Failed to decode: {!r}".format(line))
                error_count += 1

        logger.debug("{}: read {} lines".format(byte_io.name, line_count))
        if error_count > 0:
            message.error("adblock: {} read errors for {}".format(
                error_count, byte_io.name)) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:30,代码来源:adblock.py


示例18: read

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def read(self, file_name: str) -> List[Optional[InstanceContainer]]:
        """Reads a cura profile from a file and returns it.

        :param file_name: The file to read the cura profile from.
        :return: The cura profiles that were in the file, if any. If the file
            could not be read or didn't contain a valid profile, ``None`` is
            returned.
        """

        try:
            with zipfile.ZipFile(file_name, "r") as archive:
                results = []  # type: List[Optional[InstanceContainer]]
                for profile_id in archive.namelist():
                    with archive.open(profile_id) as f:
                        serialized = f.read()
                    upgraded_profiles = self._upgradeProfile(serialized.decode("utf-8"), profile_id) #After upgrading it may split into multiple profiles.
                    for upgraded_profile in upgraded_profiles:
                        serialization, new_id = upgraded_profile
                        profile = self._loadProfile(serialization, new_id)
                        if profile is not None:
                            results.append(profile)
                return results

        except zipfile.BadZipFile:
            # It must be an older profile from Cura 2.1.
            with open(file_name, encoding = "utf-8") as fhandle:
                serialized_bytes = fhandle.read()
            return [self._loadProfile(serialized, profile_id) for serialized, profile_id in self._upgradeProfile(serialized_bytes, file_name)] 
开发者ID:Ultimaker,项目名称:Cura,代码行数:30,代码来源:CuraProfileReader.py


示例19: read_wheel_metadata_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def read_wheel_metadata_file(source, path):
    # type: (ZipFile, str) -> bytes
    try:
        return source.read(path)
        # BadZipFile for general corruption, KeyError for missing entry,
        # and RuntimeError for password-protected files
    except (BadZipFile, KeyError, RuntimeError) as e:
        raise UnsupportedWheel(
            "could not read {!r} file: {!r}".format(path, e)
        ) 
开发者ID:pypa,项目名称:pipenv,代码行数:12,代码来源:wheel.py


示例20: download_archive

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def download_archive(
    archive_url: str,
    archive_extract_dir: Path,
    junk_paths: bool = False,
    filename: Optional[str] = None,
) -> Path:
    """
    Save an archive in the given directory and extract its contents.  Automatically
    retry the download once if the file comes back corrupted (in case it's left over
    from a partial download that was cancelled before).

    Args:
      archive_url: URL for the archive.
      archive_extract_dir: Download the archive and extract it to this directory.
      junk_paths: If True, disregard the archive's internal directory hierarchy
        and extract all files directly to the output directory.
      filename: If given, store the downloaded file under this name instead of
        one automatically inferred from the URL.

    Returns:
      Path to the directory containing the extracted file contents.
    """
    download_path = download_file(archive_url, filename=filename)
    try:
        return extract_archive(
            download_path, archive_extract_dir, junk_paths=junk_paths
        )
    except (zipfile.BadZipFile, tarfile.ReadError, OSError, EOFError):
        LOGGER.warning(
            f"Downloaded archive at '{download_path}' is corrupted.  Retrying..."
        )
        download_path.unlink()
        download_path = download_file(archive_url, filename=filename)
        return extract_archive(
            download_path, archive_extract_dir, junk_paths=junk_paths
        ) 
开发者ID:RTIInternational,项目名称:gobbli,代码行数:38,代码来源:util.py


示例21: test_close_on_exception

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_close_on_exception(self):
        """Check that the zipfile is closed if an exception is raised in the
        'with' block."""
        with zipfile.ZipFile(TESTFN2, "w") as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                zipfp.writestr(fpath, fdata)

        try:
            with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
                raise zipfile.BadZipFile()
        except zipfile.BadZipFile:
            self.assertIsNone(zipfp2.fp, 'zipfp is not closed') 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:14,代码来源:test_zipfile.py


示例22: test_close_erroneous_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_close_erroneous_file(self):
        # This test checks that the ZipFile constructor closes the file object
        # it opens if there's an error in the file.  If it doesn't, the
        # traceback holds a reference to the ZipFile object and, indirectly,
        # the file object.
        # On Windows, this causes the os.unlink() call to fail because the
        # underlying file is still open.  This is SF bug #412214.
        #
        with open(TESTFN, "w") as fp:
            fp.write("this is not a legal zip file\n")
        try:
            zf = zipfile.ZipFile(TESTFN)
        except zipfile.BadZipFile:
            pass 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:16,代码来源:test_zipfile.py


示例23: test_damaged_zipfile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_damaged_zipfile(self):
        """Check that zipfiles with missing bytes at the end raise BadZipFile."""
        # - Create a valid zip file
        fp = io.BytesIO()
        with zipfile.ZipFile(fp, mode="w") as zipf:
            zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
        zipfiledata = fp.getvalue()

        # - Now create copies of it missing the last N bytes and make sure
        #   a BadZipFile exception is raised when we try to open it
        for N in range(len(zipfiledata)):
            fp = io.BytesIO(zipfiledata[:N])
            self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:15,代码来源:test_zipfile.py


示例24: test_empty_file_raises_BadZipFile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_empty_file_raises_BadZipFile(self):
        f = open(TESTFN, 'w')
        f.close()
        self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)

        with open(TESTFN, 'w') as fp:
            fp.write("short file")
        self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:10,代码来源:test_zipfile.py


示例25: export_presets

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def export_presets(names, archive):
    """Export presets-files into an archive.

    :param names: The presets to be exported
    :type names: typing.Iterable[Str]
    :param archive: The path of the archive
    :type archive: str
    """
    if names:
        try:
            with ZipFile(archive, mode='w') as archive:
                for name in names:
                    archive.write(preset_path(name), name)
        except(OSError, BadZipFile) as e:
            raise PresetExportError(str(e)) 
开发者ID:FrancescoCeruti,项目名称:linux-show-player,代码行数:17,代码来源:lib.py


示例26: import_presets

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def import_presets(archive, overwrite=True):
    """Import presets for an archive.

    :param archive: The archive path
    :type archive: str
    :param overwrite: Overwrite existing files
    :type overwrite: bool
    """
    try:
        with ZipFile(archive) as archive:
            for member in archive.namelist():
                if not (preset_exists(member) and not overwrite):
                    archive.extract(member, path=PRESETS_DIR)
    except(OSError, BadZipFile) as e:
        raise PresetImportError(str(e)) 
开发者ID:FrancescoCeruti,项目名称:linux-show-player,代码行数:17,代码来源:lib.py



注:本文中的zipfile.BadZipFile方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。