代码:
def zip_dir(dirname,zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else :
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name))
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
zf.write(tar,arcname)
zf.close()
def unzip_file(zipfilename, unziptodir):
if not os.path.exists(unziptodir): os.mkdir(unziptodir)
zfobj = zipfile.ZipFile(zipfilename)
for name in zfobj.namelist():
name = name.replace('\\','/')
if name.endswith('/'):
os.mkdir(os.path.join(unziptodir, name))
else:
ext_filename = os.path.join(unziptodir, name)
ext_dir= os.path.dirname(ext_filename)
if not os.path.exists(ext_dir) : os.mkdir(ext_dir)
outfile = open(ext_filename, 'wb')
outfile.write(zfobj.read(name))
outfile.close()
使用-压缩:
if __name__ == '__main__':
zip_dir(r'E:/temp077/target_dir',r'E:/temp055/temp.zip')
# unzip_file(r'E:/temp077/temp.zip',r'E:/temp066')
print('---------------------- ending file_tools.py')
pass
?使用-解压缩:
if __name__ == '__main__':
# zip_dir(r'E:/temp077/target_dir',r'E:/temp055/temp.zip')
unzip_file(r'E:/temp055/temp.zip',r'E:/temp066')
print('---------------------- ending file_tools.py')
pass
注意:如果压缩包中的文件夹为空,解压缩后不会把该文件夹解压出来?
|