#!/usr/bin/env python import zipfile import os # create a compress file for /etc z = zipfile.ZipFile('/root/etc.zip', 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk('/etc'): for file in files: z.write(os.path.join(root, file)) z.close() # check the name list of the compressed file 'etc.zip' z = zipfile.ZipFile('/root/etc.zip') for name in z.namelist(): print name z.close() # viewing compressed information via 'zipinfo object' z = zipfile.ZipFile('/root/etc.zip') for i in z.infolist(): print i.filename, i.date_time, i.compress_type z.close() # extractall files to /tmp directory z = zipfile.ZipFile('/root/etc.zip') z.extractall(path='/tmp') z.close()
注意:用os.walk方式压缩的文件,不包括空目录(换句话说:如果一个目录下没有文件,该空目录不会被放入压缩文件),而用tarfile,不管是否为空目录都会打包进去