Python zipfile.ZIP_STORED Examples

The following are 30 code examples of zipfile.ZIP_STORED(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module zipfile , or try the search function .
Example #1
Source File: test_zipfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_extract_all(self):
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                zipfp.writestr(fpath, fdata)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            zipfp.extractall()
            for fpath, fdata in SMALL_TEST_DATA:
                outfile = os.path.join(os.getcwd(), fpath)

                with open(outfile, "rb") as fid:
                    self.assertEqual(fdata, fid.read())
                os.remove(outfile)

        # remove the test file subdirectories
        rmtree(os.path.join(os.getcwd(), 'ziptest2dir')) 
Example #2
Source File: test_zipfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_append_to_concatenated_zip_file(self):
        with io.BytesIO() as bio:
            with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
                zipfp.write(TESTFN, TESTFN)
            zipfiledata = bio.getvalue()
        data = b'I am not a ZipFile!'*1000000
        with open(TESTFN2, 'wb') as f:
            f.write(data)
            f.write(zipfiledata)

        with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
            self.assertEqual(zipfp.namelist(), [TESTFN])
            zipfp.writestr('strfile', self.data)

        with open(TESTFN2, 'rb') as f:
            self.assertEqual(f.read(len(data)), data)
            zipfiledata = f.read()
        with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
            self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
            self.assertEqual(zipfp.read(TESTFN), self.data)
            self.assertEqual(zipfp.read('strfile'), self.data) 
Example #3
Source File: test_zipfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_append_to_non_zip_file(self):
        """Test appending to an existing file that is not a zipfile."""
        # NOTE: this test fails if len(d) < 22 because of the first
        # line "fpin.seek(-22, 2)" in _EndRecData
        data = 'I am not a ZipFile!'*10
        with open(TESTFN2, 'wb') as f:
            f.write(data)

        with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
            zipfp.write(TESTFN, TESTFN)

        with open(TESTFN2, 'rb') as f:
            f.seek(len(data))
            with zipfile.ZipFile(f, "r") as zipfp:
                self.assertEqual(zipfp.namelist(), [TESTFN])
                self.assertEqual(zipfp.read(TESTFN), self.data)
        with open(TESTFN2, 'rb') as f:
            self.assertEqual(f.read(len(data)), data)
            zipfiledata = f.read()
        with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
            self.assertEqual(zipfp.namelist(), [TESTFN])
            self.assertEqual(zipfp.read(TESTFN), self.data) 
Example #4
Source File: test_zipfile.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_extract(self):
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                zipfp.writestr(fpath, fdata)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                writtenfile = zipfp.extract(fpath)

                # make sure it was written to the right place
                correctfile = os.path.join(os.getcwd(), fpath)
                correctfile = os.path.normpath(correctfile)

                self.assertEqual(writtenfile, correctfile)

                # make sure correct data is in correct file
                self.assertEqual(fdata, open(writtenfile, "rb").read())
                os.remove(writtenfile)

        # remove the test file subdirectories
        shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir')) 
Example #5
Source File: test_zipfile.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_extract_unicode_filenames(self):
        fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
        content = 'Test for unicode filename'
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fname in fnames:
                zipfp.writestr(fname, content)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            for fname in fnames:
                writtenfile = zipfp.extract(fname)

                # make sure it was written to the right place
                correctfile = os.path.join(os.getcwd(), fname)
                correctfile = os.path.normpath(correctfile)
                self.assertEqual(writtenfile, correctfile)

                self.check_file(writtenfile, content)
                os.remove(writtenfile) 
Example #6
Source File: test_zipfile.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_open_via_zip_info(self):
        # Create the ZIP archive
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            zipfp.writestr("name", "foo")
            zipfp.writestr("name", "bar")

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            infos = zipfp.infolist()
            data = ""
            for info in infos:
                with zipfp.open(info) as f:
                    data += f.read()
            self.assertTrue(data == "foobar" or data == "barfoo")
            data = ""
            for info in infos:
                data += zipfp.read(info)
            self.assertTrue(data == "foobar" or data == "barfoo") 
Example #7
Source File: test_zipfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_extract(self):
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                zipfp.writestr(fpath, fdata)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                writtenfile = zipfp.extract(fpath)

                # make sure it was written to the right place
                correctfile = os.path.join(os.getcwd(), fpath)
                correctfile = os.path.normpath(correctfile)

                self.assertEqual(writtenfile, correctfile)

                # make sure correct data is in correct file
                with open(writtenfile, "rb") as fid:
                    self.assertEqual(fdata, fid.read())
                os.remove(writtenfile)

        # remove the test file subdirectories
        rmtree(os.path.join(os.getcwd(), 'ziptest2dir')) 
Example #8
Source File: test_zipfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_open_via_zip_info(self):
        # Create the ZIP archive
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            zipfp.writestr("name", "foo")
            with check_warnings(('', UserWarning)):
                zipfp.writestr("name", "bar")
            self.assertEqual(zipfp.namelist(), ["name"] * 2)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            infos = zipfp.infolist()
            data = ""
            for info in infos:
                with zipfp.open(info) as f:
                    data += f.read()
            self.assertTrue(data == "foobar" or data == "barfoo")
            data = ""
            for info in infos:
                data += zipfp.read(info)
            self.assertTrue(data == "foobar" or data == "barfoo") 
Example #9
Source File: test_zipfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_extract_unicode_filenames(self):
        fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
        content = 'Test for unicode filename'
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fname in fnames:
                zipfp.writestr(fname, content)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            for fname in fnames:
                writtenfile = zipfp.extract(fname)

                # make sure it was written to the right place
                correctfile = os.path.join(os.getcwd(), fname)
                correctfile = os.path.normpath(correctfile)
                self.assertEqual(writtenfile, correctfile)

                self.check_file(writtenfile, content)
                os.remove(writtenfile) 
Example #10
Source File: mangascrapper.py    From MangaScrapper with Apache License 2.0 6 votes vote down vote up
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) 
Example #11
Source File: __init__.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def assemble_my_parts(self):
        """Assemble the `self.parts` dictionary.  Extend in subclasses.
        """
        writers.Writer.assemble_parts(self)
        f = tempfile.NamedTemporaryFile()
        zfile = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
        self.write_zip_str(zfile, 'mimetype', self.MIME_TYPE,
            compress_type=zipfile.ZIP_STORED)
        content = self.visitor.content_astext()
        self.write_zip_str(zfile, 'content.xml', content)
        s1 = self.create_manifest()
        self.write_zip_str(zfile, 'META-INF/manifest.xml', s1)
        s1 = self.create_meta()
        self.write_zip_str(zfile, 'meta.xml', s1)
        s1 = self.get_stylesheet()
        self.write_zip_str(zfile, 'styles.xml', s1)
        self.store_embedded_files(zfile)
        self.copy_from_stylesheet(zfile)
        zfile.close()
        f.seek(0)
        whole = f.read()
        f.close()
        self.parts['whole'] = whole
        self.parts['encoding'] = self.document.settings.output_encoding
        self.parts['version'] = docutils.__version__ 
Example #12
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_open_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_open_test(f, zipfile.ZIP_STORED) 
Example #13
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_absolute_arcnames(self):
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            zipfp.write(TESTFN, "/absolute")

        with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
            self.assertEqual(zipfp.namelist(), ["absolute"]) 
Example #14
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_iterlines_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_iterlines_test(f, zipfile.ZIP_STORED) 
Example #15
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_readlines_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readlines_test(f, zipfile.ZIP_STORED) 
Example #16
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_testzip_with_bad_crc_stored(self):
        self.check_testzip_with_bad_crc(zipfile.ZIP_STORED) 
Example #17
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_read_return_size_stored(self):
        self.check_read_return_size(zipfile.ZIP_STORED) 
Example #18
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_read_with_bad_crc_stored(self):
        self.check_read_with_bad_crc(zipfile.ZIP_STORED) 
Example #19
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_ignores_newline_at_end(self):
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            zipfp.write(TESTFN, TESTFN)
        with open(TESTFN2, 'a') as f:
            f.write("\r\n\00\00\00")
        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            self.assertIsInstance(zipfp, zipfile.ZipFile) 
Example #20
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_readline_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readline_test(f, zipfile.ZIP_STORED) 
Example #21
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_readline_read_stored(self):
        # Issue #7610: calls to readline() interleaved with calls to read().
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readline_read_test(f, zipfile.ZIP_STORED) 
Example #22
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_random_open_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_random_open_test(f, zipfile.ZIP_STORED) 
Example #23
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_open_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_open_test(f, zipfile.ZIP_STORED) 
Example #24
Source File: test_zipfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_test(f, zipfile.ZIP_STORED) 
Example #25
Source File: test_zipimport.py    From BinderFilter with MIT License 5 votes vote down vote up
def testAFakeZlib(self):
        #
        # This could cause a stack overflow before: importing zlib.py
        # from a compressed archive would cause zlib to be imported
        # which would find zlib.py in the archive, which would... etc.
        #
        # This test *must* be executed first: it must be the first one
        # to trigger zipimport to import zlib (zipimport caches the
        # zlib.decompress function object, after which the problem being
        # tested here wouldn't be a problem anymore...
        # (Hence the 'A' in the test method name: to make it the first
        # item in a list sorted by name, like unittest.makeSuite() does.)
        #
        # This test fails on platforms on which the zlib module is
        # statically linked, but the problem it tests for can't
        # occur in that case (builtin modules are always found first),
        # so we'll simply skip it then. Bug #765456.
        #
        if "zlib" in sys.builtin_module_names:
            return
        if "zlib" in sys.modules:
            del sys.modules["zlib"]
        files = {"zlib.py": (NOW, test_src)}
        try:
            self.doTest(".py", files, "zlib")
        except ImportError:
            if self.compression != ZIP_DEFLATED:
                self.fail("expected test to not raise ImportError")
        else:
            if self.compression != ZIP_STORED:
                self.fail("expected test to raise ImportError") 
Example #26
Source File: azure_utils.py    From learning2run with MIT License 5 votes vote down vote up
def make_archive(source_path, dest_path):
    if source_path.endswith(os.path.sep):
        source_path = source_path.rstrip(os.path.sep)
    prefix_path = os.path.dirname(source_path)
    with zipfile.ZipFile(dest_path, "w", compression=zipfile.ZIP_STORED) as zf:
        if os.path.isdir(source_path):
            for dirname, subdirs, files in os.walk(source_path):
                zf.write(dirname, os.path.relpath(dirname, prefix_path))
                for filename in files:
                    filepath = os.path.join(dirname, filename)
                    zf.write(filepath, os.path.relpath(filepath, prefix_path))
        else:
            zf.write(source_path, os.path.relpath(source_path, prefix_path)) 
Example #27
Source File: install.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, file, mode="r",
                 compression=zipfile.ZIP_STORED,
                 allowZip64=False):
        zipfile.ZipFile.__init__(self, file, mode, compression, allowZip64)

        self.strict = False
        self._expected_hashes = {}
        self._hash_algorithm = hashlib.sha256 
Example #28
Source File: bdist_egg.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
                 mode='w'):
    """Create a zip file from all the files under 'base_dir'.  The output
    zip file will be named 'base_dir' + ".zip".  Uses either the "zipfile"
    Python module (if available) or the InfoZIP "zip" utility (if installed
    and found on the default search path).  If neither tool is available,
    raises DistutilsExecError.  Returns the name of the output zip file.
    """
    import zipfile

    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
    log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)

    def visit(z, dirname, names):
        for name in names:
            path = os.path.normpath(os.path.join(dirname, name))
            if os.path.isfile(path):
                p = path[len(base_dir) + 1:]
                if not dry_run:
                    z.write(path, p)
                log.debug("adding '%s'", p)

    compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
    if not dry_run:
        z = zipfile.ZipFile(zip_filename, mode, compression=compression)
        for dirname, dirs, files in os.walk(base_dir):
            visit(z, dirname, files)
        z.close()
    else:
        for dirname, dirs, files in os.walk(base_dir):
            visit(None, dirname, files)
    return zip_filename 
Example #29
Source File: viewer_tools.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_attachments_zipfile(attachments, temporary_file=None):
    if not temporary_file:
        temporary_file = NamedTemporaryFile()

    storage = get_storage_class()()
    with zipfile.ZipFile(temporary_file, 'w', zipfile.ZIP_STORED, allowZip64=True) as zip_file:
        for attachment in attachments:
            if storage.exists(attachment.media_file.name):
                try:
                    with storage.open(attachment.media_file.name, 'rb') as source_file:
                        zip_file.writestr(attachment.media_file.name, source_file.read())
                except Exception, e:
                    report_exception("Error adding file \"{}\" to archive.".format(attachment.media_file.name), e)

    # Be kind; rewind. 
Example #30
Source File: install.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def __init__(self, file, mode="r",
                 compression=zipfile.ZIP_STORED,
                 allowZip64=False):
        zipfile.ZipFile.__init__(self, file, mode, compression, allowZip64)

        self.strict = False
        self._expected_hashes = {}
        self._hash_algorithm = hashlib.sha256