import zipfile, tarfile
(1)读取一个zip压缩包的指定文件,如果这个文件是XML格式,使用DOM从中取数据
def get_ifix_ids_by_zip_path(fix_path):
ifix_ids = []
zf = zipfile.ZipFile(fix_path)
try:
repository = zf.read("repository.xml")
repo = xml.dom.minidom.parseString(repository)
repositoryDigest = repo.getElementsByTagName("repositoryDigest")[0]
for x in repositoryDigest.childNodes:
try:
ifix_ids.append(x.getElementsByTagName("fix")[0].getAttribute("id"))
except:
pass
except:
e = sys.exc_info()
logger.error(_("%s is not a valid interim fix; ignore it when you are installing interim fixes.") % fix_path)
logger.debug(e)
return ifix_ids
(2) 判断一个文件是否是tar或zip
def is_compressedfile(f):
if os.path.isfile(f):
return zipfile.is_zipfile(f) or tarfile.is_tarfile(f)
return False
(3)检查一个zip文件是否包含指定文件名的文件
ifix_zip = zipfile.ZipFile(ifix, 'r')
return True if "repository.xml" in [x.filename for x in ifix_zip.infolist()] else False
(4)解压zip文件到指定的目录
with open(ifix["path"], "rb") as candidate:
zipfile.ZipFile(candidate).extractall(ifix_path)
(5)解压tar文件到指定的目录
tarfile.open(ifix["path"], 'r|gz').extractall(path=ifix_path)