1、使用gzip创建一个文件:
示例代码:
import gzip
# 创建一个gzip文件
content = "Hello world!"
f = gzip.open('file.txt.gz', 'wb')
# f.write(content) # 直接这样写报错
f.write(content.encode())
f.close()
运行结果:
2、对目前存在的文件进行压缩和解压
2.1 压缩数据容量
示例代码:
import gzip
def zip_file(path, new_path):
with open(new_path, 'wb') as wf:
with open(path, 'rb') as rf:
data = rf.read()
# 压缩数据
data_comp = gzip.compress(data)
wf.write(data_comp)
path = 'data/zip_file_save/big_data.txt'
new_path = 'data/zip_file_save/new_big_data.txt'
zip_file(path, new_path)
运行结果:
2.2 压缩成.gz文件
示例代码:
import gzip
# 压缩一个存在的压缩包
f_in = open('file.txt', 'rb')
f_zip = gzip.open('file.txt.gz', 'wb')
f_zip.writelines(f_in)
f_zip.close()
f_in.close()
运行结果:
2.3 解压.gz文件(函数封装)
示例代码:
import os
import gzip
def unzip_gz_file(path, new_path):
count = 0
try:
for f_path in os.listdir(path):
if '.gz' in f_path:
try:
with gzip.GzipFile(fileobj=open(path + "/" + f_path, 'rb'), mode='rb') as g:
with open(new_path + "/" + f_path.replace(".gz", ""), "wb") as f:
f.write(g.read())
print(count, f"文件{f_path} 解压完成...")
except Exception as e:
print(f_path, e)
count += 1
except Exception as e:
print(e)
else:
print("文件全部解压完成!")
path = 'data/zip_file_save'
new_path = 'data/zip_file_save/unzip_file'
unzip_gz_file(path, new_path)
运行结果:
2.4 解压.zip文件(函数封装)
示例代码:
import os
import zipfile
def unzip_file(path, new_path):
count = 0
try:
for f_path in os.listdir(path):
if '.zip' in f_path:
try:
with zipfile.ZipFile(path + '/' + f_path) as zip_file1:
zip_file1.extract(zip_file1.namelist()[0], new_path)
print(count, f"文件{f_path} 解压完成...")
except Exception as e:
print(f_path, e)
count += 1
except Exception as e:
print(e)
else:
print("文件全部解压完成!")
path = 'data/zip_file_save'
new_path = 'data/zip_file_save/unzip_file'
unzip_file(path, new_path)
运行结果:
3、读取压缩文件中的数据
示例代码
import gzip
# 读取压缩文件中的数据
f = gzip.open('file.txt.gz', 'rb')
data = f.read()
f.close()
print(data)
print(data.decode())
运行结果: