打包
import zlib
import os
def compress_folder(input_folder, output_filename):
"""
使用 DEFLATE 算法压缩文件夹下的所有文件。
Parameters:
input_folder: str
要压缩的文件夹路径。
output_filename: str
输出压缩文件名。
"""
# 创建一个空的字节串,用于存储所有文件的压缩数据
compressed_data = bytearray()
# 遍历文件夹下的所有文件
for root, dirs, files in os.walk(input_folder):
for file in files:
# 构建文件的完整路径
file_path = os.path.join(root, file)
# 读取文件内容
with open(file_path, 'rb') as f:
file_data = f.read()
# 使用 DEFLATE 算法压缩文件内容
compressed_data += zlib.compress(file_data)
# 将所有文件的压缩数据写入到输出文件中
with open(output_filename, 'wb') as f_out:
f_out.write(compressed_data)
# 指定要压缩的文件夹路径和输出文件名
input_folder = 'D:/soft/AI/workspace/packagetest/package'
output_filename = 'D:/soft/AI/workspace/packagetest/package.pg'
# 执行压缩操作
compress_folder(input_folder, output_filename)
解压
import zlib
import os
import struct
def compress_folder(input_folder, output_filename):
compressed_data = bytearray()
for root, dirs, files in os.walk(input_folder):
for file in files:
file_path = os.path.join(root, file)
with open(file_path, 'rb') as f:
file_data = f.read()
compressed_block = zlib.compress(file_data)
compressed_data += struct.pack('<I', len(compressed_block)) + compressed_block
with open(output_filename, 'wb') as f_out:
f_out.write(compressed_data)
def decompress_folder(input_filename, output_folder):
with open(input_filename, 'rb') as f_in:
compressed_data = f_in.read()
offset = 0
file_counter = 1 # 用于生成唯一文件名
while offset < len(compressed_data):
# 每个压缩块的长度信息(4字节)
block_length = struct.unpack('<I', compressed_data[offset:offset+4])[0]
offset += 4
# 解压缩块的数据
compressed_block = compressed_data[offset:offset+block_length]
offset += block_length
# 解压缩数据
try:
decompressed_data = zlib.decompress(compressed_block)
except zlib.error as e:
print(f"解压缩块 {file_counter} 失败:{e}")
continue
# 生成唯一文件名
file_name = f"file_{file_counter}.dat"
file_counter += 1
# 写入文件
file_path = os.path.join(output_folder, file_name)
with open(file_path, 'wb') as f_out:
f_out.write(decompressed_data)
if __name__ == "__main__":
input_folder = 'D:/soft/AI/workspace/packagetest/package'
output_filename = 'D:/soft/AI/workspace/packagetest/package.pg'
output_folder = 'D:/soft/AI/workspace/packagetest/extracted'
try:
# 检查并创建目标文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 压缩文件夹
compress_folder(input_folder, output_filename)
# 解压缩文件夹
decompress_folder(output_filename, output_folder)
print("操作成功!")
except Exception as e:
print(f"操作失败:{e}")