python項目1:自動解壓並刪除壓縮包

目的:實現壓縮包的自動解壓及刪除。函數

思路:獲取壓縮包 > 解壓 > 刪除壓縮包spa

代碼實現:此處代碼實現前提爲.py文件和壓縮包在同一文件夾code

# 導入須要的包
import os
import shutil
import time

# 定義查找函數
def scan_file():
    files = os.listdir()
    for f in files:
        if f.endswith('.zip'):
            return f

# 定義解壓函數
def unzip_it(f):
    folder_name = f.split('.')[0]
    target_path = './' + folder_name
    os.makedirs(target_path)
    shutil.unpack_archive(f, target_path)

# 定義刪除函數
def delete_file(f):
    os.remove(f)

# 讓代碼持續運行,一旦發現壓縮包及時進行相關操做。
while True:
    zip_file = scan_file()
    if zip_file:
        unzip_it(zip_file)
        delete_file(zip_file)
    time.sleep(1) # 延時函數,減小內存佔用,避免卡頓

結果:.zip文件一旦出現,則馬上被解壓並刪除blog

相關文章
相關標籤/搜索