压缩文件
不保留目录压缩
import os
import zipfile
def compress_files(output_path, source_path):
# 更改当前工作目录到源文件路径
os.chdir(source_path)
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
# 遍历当前目录下所有文件,并将它们添加到压缩文件中
for file in os.listdir(source_path):
file_path = file
zipf.write(file_path)
return True
compress_files('compress.zip', '/path/to/source/directory')
保留目录压缩
import os
import zipfile
def compress_files(output_path, source_path):
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(source_path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path)
return True
# 调用函数压缩指定路径下的所有文件
compress_files('compressed.zip', '/path/to/source/directory')
解压文件
def unzip_file(zip_src, dst_dir):
r = zipfile.is_zipfile(zip_src)
if r:
fz = zipfile.ZipFile(zip_src, 'r')
for file in fz.namelist():
global zipRealsePath,zipRealseFilenameList
zipRealsePath = file
zipRealseFilenameList.append(file.split('/')[-1])
fz.extract(file, dst_dir)
fz.close()
return True
else:
return False