溫馨提示×

怎么用python遞歸解壓所有文件

小億
174
2023-10-27 00:50:07
欄目: 編程語言

要用Python遞歸解壓所有文件,你可以使用zipfile模塊來操作壓縮文件。下面是一個使用遞歸的示例代碼:

import os
import zipfile

def unzip_all_files(directory):
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        if os.path.isfile(item_path) and item.endswith('.zip'):
            # 打開壓縮文件
            with zipfile.ZipFile(item_path, 'r') as zip_ref:
                # 解壓文件到當前目錄
                zip_ref.extractall(directory)
            # 刪除壓縮文件
            os.remove(item_path)
        elif os.path.isdir(item_path):
            # 遞歸調用解壓函數
            unzip_all_files(item_path)

# 指定要解壓的目錄
directory_to_unzip = 'path/to/directory'
unzip_all_files(directory_to_unzip)

在上面的代碼中,首先定義了一個unzip_all_files函數,該函數接受一個目錄路徑作為參數。然后,遍歷目錄中的所有項目,如果是一個壓縮文件(以.zip結尾),將其解壓到當前目錄,并刪除原始壓縮文件。如果是一個子目錄,則遞歸調用unzip_all_files函數以解壓其中的文件。最后,指定要解壓縮的目錄,并調用unzip_all_files函數來開始解壓。

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