共計 717 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
要用 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:
# 解壓文件到當(dāng)前目錄
zip_ref.extractall(directory)
# 刪除壓縮文件
os.remove(item_path)
elif os.path.isdir(item_path):
# 遞歸調(diào)用解壓函數(shù)
unzip_all_files(item_path)
# 指定要解壓的目錄
directory_to_unzip = 'path/to/directory'
unzip_all_files(directory_to_unzip)
在上面的代碼中,首先定義了一個 unzip_all_files
函數(shù),該函數(shù)接受一個目錄路徑作為參數(shù)。然后,遍歷目錄中的所有項目,如果是一個壓縮文件(以 .zip
結(jié)尾),將其解壓到當(dāng)前目錄,并刪除原始壓縮文件。如果是一個子目錄,則遞歸調(diào)用 unzip_all_files
函數(shù)以解壓其中的文件。最后,指定要解壓縮的目錄,并調(diào)用 unzip_all_files
函數(shù)來開始解壓。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完