You can download this code by clicking the button below.
This code is now available for download.
This function creates a ZIP file that includes a file named example.txt, and then extracts the contents of the ZIP file.
Technology Stack : zipfile
Code Type : Function
Code Difficulty : Intermediate
def zipfile_create_extract(filename, mode='w', compression='zip', compresslevel=9):
"""
创建一个ZIP文件并提取文件内容。
:param filename: ZIP文件名。
:param mode: 'w'表示创建新文件,'a'表示追加到现有文件。
:param compression: 压缩方法,默认为'zip'。
:param compresslevel: 压缩级别,默认为9,最高压缩。
"""
import zipfile
with zipfile.ZipFile(filename, mode, compression=compression, compresslevel=compresslevel) as zipf:
zipf.write('example.txt', arcname='example.txt')
with zipf.open('example.txt') as f:
print(f.read())
with zipfile.ZipFile(filename, 'r') as zipf:
for file_info in zipf.infolist():
print(f"Extracting {file_info.filename}")
zipf.extract(file_info)