Python zipfile.namelist() Examples

The following are 7 code examples of zipfile.namelist(). 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: data.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, zipfile, entry=''):
        """
        Create a new path pointer pointing at the specified entry
        in the given zipfile.

        :raise IOError: If the given zipfile does not exist, or if it
        does not contain the specified entry.
        """
        if isinstance(zipfile, string_types):
            zipfile = OpenOnDemandZipFile(os.path.abspath(zipfile))

        # Normalize the entry string, it should be relative:
        entry = normalize_resource_name(entry, True, '/').lstrip('/')

        # Check that the entry exists:
        if entry:
            try:
                zipfile.getinfo(entry)
            except Exception:
                # Sometimes directories aren't explicitly listed in
                # the zip file.  So if `entry` is a directory name,
                # then check if the zipfile contains any files that
                # are under the given directory.
                if (entry.endswith('/') and
                        [n for n in zipfile.namelist() if n.startswith(entry)]):
                    pass  # zipfile contains a file in that directory.
                else:
                    # Otherwise, complain.
                    raise IOError('Zipfile %r does not contain %r' %
                                  (zipfile.filename, entry))
        self._zipfile = zipfile
        self._entry = entry 
Example #2
Source File: Crashes.py    From LuckyCAT with GNU General Public License v3.0 5 votes vote down vote up
def get_original_crash_test_case_of_zipfile(crash_test_case, original_test_case):
    import zipfile
    zipfile = zipfile.ZipFile(io.BytesIO(original_test_case))
    max_similarity = 0
    for name in zipfile.namelist():
        possible_original_test_case = zipfile.read(name)
        similarity = SequenceMatcher(None, base64.b64encode(possible_original_test_case),
                                     base64.b64encode(crash_test_case)).ratio()
        if similarity > max_similarity:
            max_similarity = similarity
            original_test_case = possible_original_test_case
    return original_test_case 
Example #3
Source File: build_test.py    From lamvery with MIT License 5 votes vote down vote up
def test_build(self):
        builder = Builder('test.zip')
        builder._runtime = RUNTIME_NODE_JS
        ok_(hasattr(builder.build(), 'read'))
        with PyZipFile(builder._zippath, 'r', compression=ZIP_DEFLATED) as zipfile:
            ok_('lambda_function.pyc' in zipfile.namelist())
            ok_('.lamvery_secret.json' in zipfile.namelist()) 
Example #4
Source File: build_test.py    From lamvery with MIT License 5 votes vote down vote up
def test_build_with_single_file(self):
        builder = Builder('test.zip', function_filename='lambda_function.py', single_file=True)
        builder.build()
        with PyZipFile(builder._zippath, 'r', compression=ZIP_DEFLATED) as zipfile:
            ok_('lambda_function.py' in zipfile.namelist())
            ok_(not ('.lamvery_secret.json' in zipfile.namelist())) 
Example #5
Source File: data.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, zipfile, entry=''):
        """
        Create a new path pointer pointing at the specified entry
        in the given zipfile.

        :raise IOError: If the given zipfile does not exist, or if it
        does not contain the specified entry.
        """
        if isinstance(zipfile, basestring):
            zipfile = OpenOnDemandZipFile(os.path.abspath(zipfile))

        # Normalize the entry string:
        entry = re.sub('(^|/)/+', r'\1', entry)

        # Check that the entry exists:
        if entry:
            try: zipfile.getinfo(entry)
            except:
                # Sometimes directories aren't explicitly listed in
                # the zip file.  So if `entry` is a directory name,
                # then check if the zipfile contains any files that
                # are under the given directory.
                if (entry.endswith('/') and
                    [n for n in zipfile.namelist() if n.startswith(entry)]):
                    pass # zipfile contains a file in that directory.
                else:
                    # Otherwise, complain.
                    raise IOError('Zipfile %r does not contain %r' %
                                  (zipfile.filename, entry))
        self._zipfile = zipfile
        self._entry = entry 
Example #6
Source File: data.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def __init__(self, zipfile, entry=''):
        """
        Create a new path pointer pointing at the specified entry
        in the given zipfile.

        :raise IOError: If the given zipfile does not exist, or if it
        does not contain the specified entry.
        """
        if isinstance(zipfile, string_types):
            zipfile = OpenOnDemandZipFile(os.path.abspath(zipfile))

        # Check that the entry exists:
        if entry:

            # Normalize the entry string, it should be relative:
            entry = normalize_resource_name(entry, True, '/').lstrip('/')

            try:
                zipfile.getinfo(entry)
            except Exception:
                # Sometimes directories aren't explicitly listed in
                # the zip file.  So if `entry` is a directory name,
                # then check if the zipfile contains any files that
                # are under the given directory.
                if entry.endswith('/') and [
                    n for n in zipfile.namelist() if n.startswith(entry)
                ]:
                    pass  # zipfile contains a file in that directory.
                else:
                    # Otherwise, complain.
                    raise IOError(
                        'Zipfile %r does not contain %r' % (zipfile.filename, entry)
                    )
        self._zipfile = zipfile
        self._entry = entry 
Example #7
Source File: import_export.py    From signac with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _analyze_zipfile_for_import(zipfile, project, schema):
    names = zipfile.namelist()

    def read_sp_manifest_file(path):
        # Must use forward slashes, not os.path.sep.
        fn_manifest = path + '/' + project.Job.FN_MANIFEST
        if fn_manifest in names:
            return json.loads(zipfile.read(fn_manifest).decode())

    if schema is None:
        schema_function = read_sp_manifest_file
    elif callable(schema):
        schema_function = _with_consistency_check(schema, read_sp_manifest_file)
    elif isinstance(schema, str):
        schema_function = _with_consistency_check(
            _make_path_based_schema_function(schema), read_sp_manifest_file)
    else:
        raise TypeError("The schema variable must be None, callable, or a string.")

    mappings = dict()
    skip_subdirs = set()

    dirs = {os.path.dirname(name) for name in names}
    for name in sorted(dirs):
        cont = False
        for skip in skip_subdirs:
            if name.startswith(skip):
                cont = True
                break
        if cont:
            continue

        sp = schema_function(name)
        if sp is not None:
            job = project.open_job(sp)
            if os.path.exists(job.workspace()):
                raise DestinationExistsError(job)
            mappings[name] = job
            skip_subdirs.add(name)

    # Check uniqueness
    if len(set(mappings.values())) != len(mappings):
        raise RuntimeError("The jobs identified with the given schema function are not unique!")

    for path, job in mappings.items():
        _names = [name for name in names if name.startswith(path)]
        yield path, _CopyFromZipFileExecutor(zipfile, path, job, _names)