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


Python zipfile.BadZipfile方法代码示例

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


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

示例1: Run

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def Run(self):
    try:
      zip_file = self._args[0]
      out_path = self._args[1]
    except IndexError:
      raise ActionError('Unable to determine desired paths from %s.' %
                        str(self._args))

    try:
      file_util.CreateDirectories(out_path)
    except file_util.Error:
      raise ActionError('Unable to create output path %s.' % out_path)

    try:
      zf = zipfile.ZipFile(zip_file)
      zf.extractall(out_path)
    except (IOError, zipfile.BadZipfile) as e:
      raise ActionError('Bad zip file given as input.  %s' % e) 
开发者ID:google,项目名称:glazier,代码行数:20,代码来源:files.py

示例2: open

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def open(self, filename):
        try:
            if self.zipmode:
                if self.verbose:
                    print( "Opening Zip archive "+filename)
                self.handle = zipfile.ZipFile(filename, 'r')
            else:
                if self.verbose:
                    print( "Opening Rar archive "+filename)
                self.handle = rarfile.RarFile(filename, 'r')

        except (struct.error, zipfile.BadZipfile, zipfile.LargeZipFile, IOError) as e:
            if self.verbose:
                print( "Exception caught in ZipFile: %s" % (repr(e)))
            self.handle = None

        return self.handle 
开发者ID:cryptax,项目名称:droidlysis,代码行数:19,代码来源:droidziprar.py

示例3: check_read_with_bad_crc

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

        # 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:IronLanguages,项目名称:ironpython2,代码行数:22,代码来源:test_zipfile.py

示例4: main

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def main():
    """
    Read input zip file, minhash the documents in it and put them in buckets
    The zip file should have been created with data_prep/prepare_blobstore_zips
    """
    try:
        filename = os.path.abspath(sys.argv[1])
    except IndexError:
        print 'filename not provided'
        exit(1)
    try:
        zip_reader = zipfile.ZipFile(filename)
    except IOError:
        print 'unable to read file {file}'.format(file = filename)
        exit(1)
    except zipfile.BadZipfile:
        print 'file {file} is not a zip file'.format(file = filename)
        exit(1)

    lsh_zipfile(PeerbeltLine, zip_reader, 'bash', filename) 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:22,代码来源:serial.py

示例5: _create_cbz_

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def _create_cbz_(dirpath, archivename):
        """
        Create a Comic Book Archive in .cbz and .cbr format (Tar Compression)

        :param dirpath: Directory location to save the the book archive.
        :param archivename: Name of the archive.
        """
        currdir = os.getcwd()
        try:
            import zlib

            compression = zipfile.ZIP_DEFLATED
        except ImportError:
            logging.warning("zlib library not available. Using ZIP_STORED compression.")
            compression = zipfile.ZIP_STORED
        try:
            with zipfile.ZipFile(archivename, "w", compression) as zf:
                os.chdir(os.path.abspath(os.path.join(dirpath, os.pardir)))
                name = os.path.basename(dirpath)
                for file in os.listdir(name):
                    zf.write(os.path.join(name, file))
        except zipfile.BadZipfile:
            logging.error("Unable to compile CBR file ")
        os.chdir(currdir) 
开发者ID:AnimeshShaw,项目名称:MangaScrapper,代码行数:26,代码来源:mangascrapper.py

示例6: _extract

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def _extract(self, filename, password):
        archive_path = _prepare_archive_at_path(filename)
        if not archive_path:
            return None
        # Extraction.
        extract_path = environ.get("TEMP", "/tmp")
        with ZipFile(archive_path, "r") as archive:
            try:
                archive.extractall(path=extract_path, pwd=password)
            except BadZipfile:
                raise Exception("Invalid Zip file")
            # Try to extract it again, but with a default password
            except RuntimeError:
                try:
                    archive.extractall(path=extract_path, pwd="infected")
                except RuntimeError as err:
                    raise Exception("Unable to extract Zip file: %s" % err)
            finally:
                self._extract_nested_archives(archive, extract_path, password)
        return archive.namelist() 
开发者ID:phdphuc,项目名称:mac-a-mal-cuckoo,代码行数:22,代码来源:zip.py

示例7: _prepare_archive_at_path

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def _prepare_archive_at_path(filename):
    """ Verifies that there's a readable zip archive at the given path.

    This function returns a new name for the archive (for most cases it's
    the same as the original one; but if an archive named "foo.zip" contains
    a file named "foo" this archive will be renamed to avoid being overwrite.
    """
    # Verify that the archive is actually readable
    try:
        with ZipFile(filename, "r") as archive:
            archive.close()
    except BadZipfile:
        return None
    # Test if zip file contains a file named as itself
    if _is_overwritten(filename):
        log.debug("ZIP file contains a file with the same name, original is \
        going to be overwrite")
        # In this case we just change the file name
        new_zip_path = filename + _random_extension()
        move(filename, new_zip_path)
        filename = new_zip_path
    return filename 
开发者ID:phdphuc,项目名称:mac-a-mal-cuckoo,代码行数:24,代码来源:zip.py

示例8: _makeArchive

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def _makeArchive(self, buffer: "io.BytesIO", root_path: str) -> Optional[ZipFile]:
        """Make a full archive from the given root path with the given name.

        :param root_path: The root directory to archive recursively.
        :return: The archive as bytes.
        """

        ignore_string = re.compile("|".join(self.IGNORED_FILES))
        try:
            archive = ZipFile(buffer, "w", ZIP_DEFLATED)
            for root, folders, files in os.walk(root_path):
                for item_name in folders + files:
                    absolute_path = os.path.join(root, item_name)
                    if ignore_string.search(absolute_path):
                        continue
                    archive.write(absolute_path, absolute_path[len(root_path) + len(os.sep):])
            archive.close()
            return archive
        except (IOError, OSError, BadZipfile) as error:
            Logger.log("e", "Could not create archive from user data directory: %s", error)
            self._showMessage(
                self.catalog.i18nc("@info:backup_failed",
                                   "Could not create archive from user data directory: {}".format(error)))
            return None 
开发者ID:Ultimaker,项目名称:Cura,代码行数:26,代码来源:Backup.py

示例9: test_invalidHeader

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def test_invalidHeader(self):
        """
        A zipfile entry with the wrong magic number should raise BadZipfile for
        readfile(), but that should not affect other files in the archive.
        """
        fn = self.makeZipFile(["test contents",
                               "more contents"])
        with zipfile.ZipFile(fn, "r") as zf:
            zeroOffset = zf.getinfo("0").header_offset
        # Zero out just the one header.
        with open(fn, "r+b") as scribble:
            scribble.seek(zeroOffset, 0)
            scribble.write(b'0' * 4)
        with zipstream.ChunkingZipFile(fn) as czf:
            self.assertRaises(zipfile.BadZipfile, czf.readfile, "0")
            with czf.readfile("1") as zfe:
                self.assertEqual(zfe.read(), b"more contents") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:19,代码来源:test_zipstream.py

示例10: test_filenameMismatch

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def test_filenameMismatch(self):
        """
        A zipfile entry with a different filename than is found in the central
        directory should raise BadZipfile.
        """
        fn = self.makeZipFile([b"test contents",
                               b"more contents"])
        with zipfile.ZipFile(fn, "r") as zf:
            info = zf.getinfo("0")
            info.filename = "not zero"
        with open(fn, "r+b") as scribble:
            scribble.seek(info.header_offset, 0)
            scribble.write(info.FileHeader())

        with zipstream.ChunkingZipFile(fn) as czf:
            self.assertRaises(zipfile.BadZipfile, czf.readfile, "0")
            with czf.readfile("1") as zfe:
                self.assertEqual(zfe.read(), b"more contents") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:20,代码来源:test_zipstream.py

示例11: test_unsupportedCompression

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def test_unsupportedCompression(self):
        """
        A zipfile which describes an unsupported compression mechanism should
        raise BadZipfile.
        """
        fn = self.mktemp()
        with zipfile.ZipFile(fn, "w") as zf:
            zi = zipfile.ZipInfo("0")
            zf.writestr(zi, "some data")
            # Mangle its compression type in the central directory; can't do
            # this before the writestr call or zipfile will (correctly) tell us
            # not to pass bad compression types :)
            zi.compress_type = 1234

        with zipstream.ChunkingZipFile(fn) as czf:
            self.assertRaises(zipfile.BadZipfile, czf.readfile, "0") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:18,代码来源:test_zipstream.py

示例12: _ParseRelationshipsXMLFile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def _ParseRelationshipsXMLFile(self, xml_data):
    """Parses the relationships XML file (_rels/.rels).

    Args:
      xml_data (bytes): data of a _rels/.rels XML file.

    Returns:
      list[str]: property file paths. The path is relative to the root of
          the ZIP file.

    Raises:
      zipfile.BadZipfile: if the relationship XML file cannot be read.
    """
    xml_root = ElementTree.fromstring(xml_data)

    property_files = []
    for xml_element in xml_root.iter():
      type_attribute = xml_element.get('Type')
      if 'properties' in repr(type_attribute):
        target_attribute = xml_element.get('Target')
        property_files.append(target_attribute)

    return property_files 
开发者ID:log2timeline,项目名称:plaso,代码行数:25,代码来源:oxml.py

示例13: 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

示例14: archive_context

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def archive_context(filename):
    """
    Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
    """
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        try:
            with ContextualZipFile(filename) as archive:
                archive.extractall()
        except zipfile.BadZipfile as err:
            if not err.args:
                err.args = ('', )
            err.args = err.args + (
                MEANINGFUL_INVALID_ZIP_ERR_MSG.format(filename),
            )
            raise

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
开发者ID:aimuch,项目名称:iAI,代码行数:33,代码来源:ez_setup.py

示例15: extract_xml_strings

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipfile [as 别名]
def extract_xml_strings(filename):
    """
    Given a string [filename], opens the file and returns a generator
    that yields tuples. A tuple is of format (year, xmldoc string). A tuple
    is returned for every valid XML doc in [filename]
    """
    # search for terminating XML tag
    endtag_regex = re.compile('^<!DOCTYPE (.*) SYSTEM')
    endtag = ''
    import zipfile
    import os
    try:
        z = zipfile.ZipFile(filename, 'r')
    except zipfile.BadZipfile as e:
        print e
        return
    xmlfilename = os.path.basename(filename)[:-4] + ".xml"
    with z.open(xmlfilename, 'r') as f:
        doc = ''  # (re)initialize current XML doc to empty string
        for line in f:
            doc += line
            endtag = endtag_regex.findall(line) if not endtag else endtag
            if not endtag:
                continue
            terminate = re.compile('^</{0}>'.format(endtag[0]))
            if terminate.findall(line):
                yield doc
                endtag = ''
                doc = ''
    z.close()

# This follows google's rules for conversion of XML to JSON 
开发者ID:dataiku,项目名称:dataiku-contrib,代码行数:34,代码来源:connector.py


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