Created
March 25, 2014 20:03
-
-
Save jvanasco/9770118 to your computer and use it in GitHub Desktop.
quick functions for dealing with zipfiles, which might be zipped with or without a leading prefix.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def filenames_has_directory(filenames, directory): | |
"""if this appears to be a directory, great | |
treat directories as / instead of os.path, because we write with '/' | |
""" | |
if directory[-1] != '/': | |
directory = directory + '/' | |
directory_len = len(directory) | |
for fname in filenames: | |
if fname[:directory_len] == directory: | |
return True | |
return False | |
def filenames_all_directory(filenames): | |
"""if this is all in a directory, returns the directory | |
otherwise, returns false | |
treat directories as / instead of os.path, because we write with '/' | |
""" | |
is_dir = False | |
shortest = min(filenames, key=len) | |
if shortest[-1] == '/': | |
shortest_len = len(shortest) | |
for i in filenames: | |
bad = False | |
if i[:shortest_len] != shortest: | |
bad = True | |
if not bad: | |
is_dir = shortest | |
return is_dir | |
class ZipfileNamedList(object): | |
""" | |
wraps a list of files from a zipfile. | |
""" | |
_common_directory = None | |
filenames_archived = None ## what is actually in the archive | |
filenames_unmasked = None ## list of files without the prefix | |
def __init__(self, filenames_archived ): | |
self.filenames_archived = filenames_archived | |
self._common_directory = filenames_all_directory( filenames_archived ) | |
if self._common_directory: | |
_common_directory_len = len(self._common_directory) | |
self.filenames_unmasked = [ i[_common_directory_len:] for i in self.filenames_archived ] | |
def has_file( self, unmasked_filename ): | |
"""expects: the desired filename in an archive (without possible prefixes) | |
returns: the actual filename in an archive (includes prefixes), or False | |
""" | |
if self._common_directory: | |
if unmasked_filename in self.filenames_unmasked: | |
masked_name = "%s%s" % ( self._common_directory, unmasked_filename ) | |
return masked_name | |
return False | |
if unmasked_filename in self.filenames_archived: | |
return unmasked_filename | |
return False | |
def has_directory( self, unmasked_directory ): | |
"""expects: the desired directory in an archive | |
returns: True or False | |
""" | |
masked_name = unmasked_directory if not self._common_directory else "%s%s" % ( self._common_directory, unmasked_directory ) | |
return filenames_has_directory( self.filenames_archived , masked_name ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment