Creating and Extracting ZIP Files with Python

  • Share this:

Code introduction


This code first creates a ZIP file and adds a file named example.txt to the ZIP. Then, it extracts the ZIP file to the specified path.


Technology Stack : The package and technology stack used in the code

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zipfile_create_and_extract(zip_path, extract_path):
    import zipfile
    import os

    # 创建ZIP文件
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        # 假设有一个文件名为example.txt
        zipf.write('example.txt', arcname='example.txt')

    # 解压ZIP文件
    with zipfile.ZipFile(zip_path, 'r') as zipf:
        zipf.extractall(extract_path)