溫馨提示×

在Python里如何異步解壓zip文件

小樊
142
2024-12-07 13:48:40
欄目: 編程語言

在Python中,您可以使用aiofiles庫來異步解壓ZIP文件。首先,確保安裝了aiofiles庫:

pip install aiofiles

然后,您可以使用以下代碼異步解壓ZIP文件:

import aiofiles
import asyncio
import zipfile

async def unzip_async(zip_file_path, dest_path):
    async with aiofiles.open(zip_file_path, mode='rb') as f:
        zip_content = await f.read()

    with zipfile.ZipFile(io.BytesIO(zip_content)) as zip_ref:
        zip_ref.extractall(dest_path)

async def main():
    zip_file_path = 'example.zip'
    dest_path = 'extracted_files'

    await unzip_async(zip_file_path, dest_path)
    print(f"ZIP file {zip_file_path} has been unzipped to {dest_path}")

if __name__ == '__main__':
    asyncio.run(main())

在這個示例中,我們首先使用aiofiles庫異步讀取ZIP文件的內容。然后,我們將ZIP內容放入一個BytesIO對象,以便將其作為文件對象傳遞給zipfile模塊。最后,我們使用zipfile模塊的extractall方法將ZIP文件解壓到指定的目標目錄。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女