本文整理汇总了Python中zipfile.ZipFile.getinfo方法的典型用法代码示例。如果您正苦于以下问题:Python ZipFile.getinfo方法的具体用法?Python ZipFile.getinfo怎么用?Python ZipFile.getinfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zipfile.ZipFile
的用法示例。
在下文中一共展示了ZipFile.getinfo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_sap_file
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def check_sap_file(sap_file_path):
"""
Checks if the file at the given path is a valid Sapelli project file.
Parameters
----------
sap_file_path : str
Path to (suspected) Sapelli project file.
Raises
------
SapelliSAPException:
When the given file does not exist, is not a ZIP archive, or does not contain PROJECT.xml.
"""
try:
if not os.path.isfile(sap_file_path):
raise SapelliSAPException('The file does not exist.')
# Check if it is a ZIP file:
zip = ZipFile(sap_file_path) # throws BadZipfile
# Check if it contains PROJECT.xml:
zip.getinfo('PROJECT.xml') # throws KeyError
except BadZipfile:
raise SapelliSAPException('The file is not a valid Sapelli project file (*.sap, *.excites or *.zip).')
except KeyError:
raise SapelliSAPException('The file is not a valid Sapelli project file (ZIP archive does not contain PROJECT.xml file).')
finally:
try:
zip.close()
except BaseException:
pass
示例2: unzip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def unzip(context, blob, pathname, compact=False, base=None, excludeExt=None, excludeList=None, compatText=False):
if excludeList is None:
excludeList = []
zipFile = ZipFile(StringIO(blob))
for member in zipFile.namelist():
filename = zipFile.getinfo(member).filename
if (excludeExt is not None and filename.lower().endswith(excludeExt)) or filename in excludeList:
continue
elif filename.find('/') != -1:
if base is not None and filename[:filename.index('/')].lower().startswith(base):
filename = filename[filename.index('/')+1:]
if not filename or (compact and '/' in filename):
continue
elif compact:
continue
elif filename.endswith('/'):
os.makedirs(os.path.join(pathname, os.path.normpath(filename)))
continue
else:
try:
os.makedirs(os.path.join(pathname, os.path.normpath(filename[:filename.rindex('/')])))
except WindowsError:
pass
if compact and compatText and (filename.endswith('.txt') or filename == 'COPYING'):
filename = '[%s] %s' % (context, filename)
with open(os.path.join(pathname, os.path.normpath(filename)), 'wb') as fp:
fp.write(zipFile.open(member).read())
zipFile.close()
示例3: aqcuire_all_resources
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def aqcuire_all_resources(self, format_dict):
import cStringIO as StringIO
from zipfile import ZipFile
# Download archive.
url = self.url(format_dict)
shapefile_online = self._urlopen(url)
zfh = ZipFile(StringIO.StringIO(shapefile_online.read()), 'r')
shapefile_online.close()
# Iterate through all scales and levels and extract relevant files.
modified_format_dict = dict(format_dict)
scales = ('c', 'l', 'i', 'h', 'f')
levels = (1, 2, 3, 4)
for scale, level in itertools.product(scales, levels):
modified_format_dict.update({'scale': scale, 'level': level})
target_path = self.target_path(modified_format_dict)
target_dir = os.path.dirname(target_path)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
for member_path in self.zip_file_contents(modified_format_dict):
ext = os.path.splitext(member_path)[1]
target = os.path.splitext(target_path)[0] + ext
member = zfh.getinfo(member_path)
with open(target, 'wb') as fh:
fh.write(zfh.open(member).read())
zfh.close()
示例4: unpack
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def unpack(dirname, callback=None):
"""unpack the files in ``packed.py`` and decompress under ``dirname``
* callback is a function of prototype function(path).
It is called before attempting to compress the file.
"""
from biz.default.packed import packed_default
fakefile = StringIO(b64decode(packed_default))
zipf = ZipFile(fakefile, "r")
for name in zipf.namelist():
try:
os.makedirs(os.path.join(dirname, os.path.dirname(name)), 0700)
except OSError:
pass
data = zipf.read(name)
filename = os.path.join(dirname, name)
if callback:
callback(filename)
mode = zipf.getinfo(name).external_attr >> 16
f = file(filename, "wb")
f.write(data)
f.close()
os.chmod(filename, mode)
zipf.close()
fakefile.close()
示例5: acquire_all_resources
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def acquire_all_resources(self, format_dict):
from zipfile import ZipFile
# Download archive.
url = self.url(format_dict)
shapefile_online = self._urlopen(url)
zfh = ZipFile(six.BytesIO(shapefile_online.read()), "r")
shapefile_online.close()
# Iterate through all scales and levels and extract relevant files.
modified_format_dict = dict(format_dict)
scales = ("c", "l", "i", "h", "f")
levels = (1, 2, 3, 4)
for scale, level in itertools.product(scales, levels):
modified_format_dict.update({"scale": scale, "level": level})
target_path = self.target_path(modified_format_dict)
target_dir = os.path.dirname(target_path)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
for member_path in self.zip_file_contents(modified_format_dict):
ext = os.path.splitext(member_path)[1]
target = os.path.splitext(target_path)[0] + ext
member = zfh.getinfo(member_path)
with open(target, "wb") as fh:
fh.write(zfh.open(member).read())
zfh.close()
示例6: get_smses
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def get_smses(self, owner_id=None):
"""
Returns all smses in form of SMS objects
The optional owner_id if given sets the owner_id field of the SMS object
"""
ret = dict(smses=[], errors=0, successful=0, error_messages=[])
owner = db.query(User).filter_by(user_id=owner_id).first()
if not owner:
raise RuntimeError("Specified owner does not exist in the DB")
owner_cell_number = UserCellNumber.get_default_number(owner_id)
zip_file = ZipFile(self.filename, 'r')
for subfilename in zip_file.namelist():
try:
log.info("Processing {} from the zip file".format(subfilename))
file_info = zip_file.getinfo(subfilename)
subfile = zip_file.open(file_info)
file_data = subfile.read().decode('utf-16')
log.debug(file_data)
msg_obj = self.parse_msg_string(file_data, owner_cell_number, owner)
msg_obj.owner_id = owner_id
ret['smses'].append(msg_obj)
ret['successful'] += 1
except Exception as exp:
ret['errors'] += 1
ret['error_messages'].append(str(exp))
return ret
示例7: main
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def main():
"""
<-- zip
See linked list
"""
f = 'channel.zip'
f = ZipFile(f, 'r')
nothing = '90052'
pattern = re.compile('Next nothing is (\d+)')
result = []
while True:
nothing += '.txt'
try:
comment = f.getinfo(nothing).comment
except IndexError:
break
if not comment in result:
result.append(comment)
nothing = f.open(nothing).read()
try:
nothing = pattern.findall(nothing)[0]
except IndexError:
break
result = [c.lower() for c in result if c.isalpha()]
print ''.join(result)
示例8: unzip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def unzip(filename):
z = ZipFile(filename)
names = z.namelist()
for path in names:
if path.startswith('__MACOSX/'):
continue
base, name = os.path.split(path)
if name.startswith('._') and\
'%s/' % name.replace('._', '', 1) in names:
continue
double = os.path.join('__MACOSX', base, '._' + name)
if double in names:
print '=> %s.bin' % path
info = z.getinfo(path)
bin = MacBinary(name)
bin.data = z.open(path, 'r').read()
bin.res = z.open(double, 'r').read()
modified = datetime.datetime(*info.date_time)
bin.modified = time.mktime(modified.timetuple())
bin.created = time.time()
if not os.path.exists(base):
os.makedirs(base)
with open('%s.bin' % path.rstrip('\r'), 'wb') as f:
f.write(bin.encode())
else:
print '-> %s' % path
z.extract(path)
示例9: publishFromDir
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def publishFromDir(self, path, dirPath):
'''
@see ICDM.publishFromDir
'''
assert isinstance(path, str) and len(path) > 0, 'Invalid content path %s' % path
assert isinstance(dirPath, str), 'Invalid directory path value %s' % dirPath
path, fullPath = self._validatePath(path)
if not isdir(dirPath):
# not a directory, see if it's a entry in a zip file
zipFilePath, inDirPath = getZipFilePath(dirPath, self.delivery.getRepositoryPath())
zipFile = ZipFile(zipFilePath)
if not inDirPath.endswith(ZIPSEP):
inDirPath = inDirPath + ZIPSEP
fileInfo = zipFile.getinfo(inDirPath)
if not fileInfo.filename.endswith(ZIPSEP):
raise IOError('Trying to publish a file from a ZIP directory path: %s' % fileInfo.filename)
self._copyZipDir(zipFilePath, inDirPath, fullPath)
assert log.debug('Success publishing ZIP dir %s (%s) to path %s', inDirPath, zipFilePath, path) or True
return
dirPath = normpath(dirPath)
assert os.access(dirPath, os.R_OK), 'Unable to read the directory path %s' % dirPath
for root, _dirs, files in os.walk(dirPath):
relPath = relpath(root, dirPath)
for file in files:
publishPath = join(path, relPath.lstrip(os.sep), file)
filePath = join(root, file)
self.publishFromFile(publishPath, filePath)
assert log.debug('Success publishing directory %s to path %s', dirPath, path) or True
示例10: publishFromFile
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def publishFromFile(self, path, filePath):
'''
@see ICDM.publishFromFile
'''
assert isinstance(path, str) and len(path) > 0, 'Invalid content path %s' % path
if not isinstance(filePath, str) and hasattr(filePath, 'read'):
return self._publishFromFileObj(path, filePath)
assert isinstance(filePath, str), 'Invalid file path value %s' % filePath
path, dstFilePath = self._validatePath(path)
dstDir = dirname(dstFilePath)
if not isdir(dstDir):
os.makedirs(dstDir)
if not isfile(filePath):
# not a file, see if it's a entry in a zip file
zipFilePath, inFilePath = getZipFilePath(filePath, self.delivery.getRepositoryPath())
zipFile = ZipFile(zipFilePath)
fileInfo = zipFile.getinfo(inFilePath)
if fileInfo.filename.endswith(ZIPSEP):
raise IOError('Trying to publish a file from a ZIP directory path: %s' % fileInfo.filename)
if not self._isSyncFile(zipFilePath, dstFilePath):
copyfileobj(zipFile.open(inFilePath), open(dstFilePath, 'w+b'))
assert log.debug('Success publishing ZIP file %s (%s) to path %s', inFilePath, zipFilePath, path) or True
return
assert os.access(filePath, os.R_OK), 'Unable to read the file path %s' % filePath
if not self._isSyncFile(filePath, dstFilePath):
copyfile(filePath, dstFilePath)
assert log.debug('Success publishing file %s to path %s', filePath, path) or True
示例11: preloadFont
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def preloadFont(cls, font, directory=DEFAULT_DIR):
"""
Load font file into memory. This can be overriden with
a superclass to create different font sources.
"""
fontPath = os.path.join(directory, font + ".flf")
if not os.path.exists(fontPath):
fontPath = os.path.join(directory, font + ".tlf")
if not os.path.exists(fontPath):
raise pyfiglet.FontNotFound("%s doesn't exist" % font)
if is_zipfile(fontPath):
z = None
try:
z = ZipFile(fontPath, "r")
data = z.read(z.getinfo(z.infolist()[0].filename))
z.close()
return data.decode("utf-8", "replace") if ST3 else data
except Exception as e:
if z is not None:
z.close()
raise pyfiglet.FontError("couldn't read %s: %s" % (fontPath, e))
else:
try:
with open(fontPath, "rb") as f:
data = f.read()
return data.decode("utf-8", "replace") if ST3 else data
except Exception as e:
raise pyfiglet.FontError("couldn't open %s: %s" % (fontPath, e))
raise pyfiglet.FontNotFound(font)
示例12: acquire_resource
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def acquire_resource(self, target_path, format_dict):
"""
Downloads the zip file and extracts the files listed in
:meth:`zip_file_contents` to the target path.
"""
import cStringIO as StringIO
from zipfile import ZipFile
target_dir = os.path.dirname(target_path)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
url = self.url(format_dict)
shapefile_online = self._urlopen(url)
zfh = ZipFile(StringIO.StringIO(shapefile_online.read()), 'r')
for member_path in self.zip_file_contents(format_dict):
ext = os.path.splitext(member_path)[1]
target = os.path.splitext(target_path)[0] + ext
member = zfh.getinfo(member_path)
with open(target, 'wb') as fh:
fh.write(zfh.open(member).read())
shapefile_online.close()
zfh.close()
return target_path
示例13: _check_test_zip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def _check_test_zip(self):
zip = ZipFile(self.zipFilename, 'r')
try:
info = zip.getinfo('image')
expect(info).to_be_truthy()
expect(info.flag_bits).to_equal(8)
expect(info.filename).to_equal('image')
expect(info.file_size).to_equal(stat(self.tiffFilename).st_size)
finally:
zip.close()
示例14: unzip
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
def unzip( filename, destination=None, report=False ):
from zipfile import ZipFile
base_dir = ""
if destination is None:
destination = os.path.dirname( filename ) #=> extraction in current directory
try:
zip = ZipFile( filename, "r" )
namelist = zip.namelist()
total_items = len( namelist ) or 1
diff = 100.0 / total_items
percent = 0
# nom du dossier racine
is_root_dir = True
if "/" in namelist[ 0 ]:
if namelist[ 0 ].endswith( "/" ):
root_dir = namelist[ 0 ]
if not root_dir.endswith( "/" ) and ( zip.getinfo( root_dir ).file_size > 0 ):
is_root_dir = False
else:
for i in namelist:
if not root_dir in i:
is_root_dir = False
break
else:
root_dir = namelist[ 0 ].split("/")[0]
else:
is_root_dir = False
# si root_dir n'est pas un dossier ou n'est pas la racine, on se base sur le nom de l'archive
base_dir = os.path.join( destination, root_dir.rstrip( "/" )[:42] ) # xbox filename limitation
if not is_root_dir:#root_dir.endswith( "/" ) and ( zip.getinfo( root_dir ).file_size > 0 ):
root_dir = os.path.basename( os.path.splitext( filename )[ 0 ] )
destination = os.path.join( destination, root_dir[:42] )
base_dir = destination
if os.path.isdir( base_dir ):
shutil2.rmtree( base_dir )
os.makedirs( base_dir )
for count, item in enumerate( namelist ):
percent += diff
if report:
if DIALOG_PROGRESS.iscanceled():
break
DIALOG_PROGRESS.update( int( percent ), _( 30188 ) % ( count + 1, total_items ), item, _( 30110 ) )
if not item.endswith( "/" ):
root, name = os.path.split( item )
directory = os.path.normpath( os.path.join( destination, root.replace(root_dir.rstrip( "/" ),root_dir.rstrip( "/" )[:42]) ) )
if not os.path.isdir( directory ): os.makedirs( directory )
filename = makeLegalFilename( os.path.join( directory, name ), True )
file( filename, "wb" ).write( zip.read( item ) )
zip.close()
del zip
return base_dir, True
except:
print_exc()
return "", False
示例15: __init__
# 需要导入模块: from zipfile import ZipFile [as 别名]
# 或者: from zipfile.ZipFile import getinfo [as 别名]
class ZipHandler:
def __init__(self, path):
self.path = path
self.zip = ZipFile(self.path, "r")
def list_files(self, sub_path):
if sub_path:
return
for name in self.zip.namelist():
if name.endswith(str("/")):
continue
yield self.decode_name(name)
def open(self, name):
name = self.encode_name(name)
return self.zip.open(name)
def exists(self, name):
name = self.encode_name(name)
try:
self.zip.getinfo(name)
except KeyError:
return False
else:
return True
def encode_name(self, name):
name = name.replace("\\", "/")
name = name.replace("%5f", "\\")
name = name.replace("%25", "%")
#name = name.encode("CP437")
name = name.encode("ISO-8859-1")
return name
def decode_name(self, name):
#name = name.decode("CP437")
name = name.decode("ISO-8859-1")
name = name.replace("%", "%25")
name = name.replace("\\", "%5f")
name = name.replace("/", os.sep)
return name