使用GzipFile()函数在Python中压缩和解压文件夹
发布时间:2023-12-27 23:24:32
在Python中,可以使用gzip模块中的GzipFile()函数来压缩和解压文件夹。GzipFile()函数用于对文件和流进行gzip压缩和解压缩操作。
下面给出一个压缩文件夹的例子:
import os
import gzip
def compress_folder(folder_path, output_path):
with gzip.GzipFile(output_path, 'wb') as output:
for root, dirs, files in os.walk(folder_path):
for file in files:
path = os.path.join(root, file)
with open(path, 'rb') as f:
output.write(f.read())
output.write(b'
') # 添加换行符,以便每个文件占一行
# 指定需要压缩的文件夹路径和输出文件路径
folder_path = '/path/to/folder'
output_path = '/path/to/output.gz'
compress_folder(folder_path, output_path)
上述代码中,compress_folder函数将指定的文件夹中的所有文件读取为二进制,然后使用GzipFile()函数将二进制数据压缩,并将压缩后的数据写入到输出文件中。
接下来,给出一个解压文件夹的例子:
import os
import gzip
def decompress_folder(input_path, output_folder):
with gzip.GzipFile(input_path, 'rb') as input:
for line in input:
file_path = os.path.join(output_folder, line.strip().decode('utf-8'))
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'wb') as output:
output.write(input.read())
# 指定需要解压的文件路径和输出文件夹路径
input_path = '/path/to/input.gz'
output_folder = '/path/to/folder'
decompress_folder(input_path, output_folder)
上述代码中,decompress_folder函数使用GzipFile()函数将输入的gzip文件解压,然后通过循环将解压后的文件逐个写入到指定的输出文件夹中。
注意:在使用上述代码时,需要替换文件路径为实际的文件路径,确保路径的正确性。
