溫馨提示×

python unzip的用法是什么

小億
178
2024-01-03 16:45:11
欄目: 編程語言

在Python中,unzip(解壓縮)是指將壓縮文件解壓到指定目錄或內存中。Python提供了多種解壓縮文件的方法,其中最常用的是使用zipfile模塊。

下面是使用zipfile模塊進行解壓縮的基本用法:

  1. 導入zipfile模塊:
import zipfile
  1. 打開壓縮文件:
with zipfile.ZipFile('example.zip', 'r') as zip_ref:
    # 這里的example.zip是要解壓的壓縮文件名或路徑,'r'表示以只讀方式打開
  1. 解壓文件到指定目錄:
zip_ref.extractall('destination_folder')
# 這里的destination_folder是要解壓到的目錄名或路徑
  1. 解壓單個文件:
zip_ref.extract('file.txt', 'destination_folder')
# 這里的file.txt是要解壓的文件名,'destination_folder'是要解壓到的目錄名或路徑

完整的示例代碼如下:

import zipfile

with zipfile.ZipFile('example.zip', 'r') as zip_ref:
    zip_ref.extractall('destination_folder')

上述代碼將解壓example.zip文件到destination_folder目錄中。

注意:解壓縮文件時,需要確保壓縮文件存在,并且指定的目錄或路徑是有效的。

0